views:

449

answers:

4

Hi Guys,

I am using rhino mocks 3.5 and am trying to throw an exception in my expectation to test some functionality in my catch block.

But for some reason it is not throwing the exception.

_xyz.stub(x => x.function(string)).throw(new exception("test string"));

So, I am stubbing out the call to the function to throw exception but it is not throwing the exception.

+2  A: 

You may need to post more information and more of your source code. My first guess would be that the method you are stubbing is never getting hit in the consumer.

As you step through the code, does the place where _xyz.function(string) is used get hit?

Phil Sandler
Yes it gets hit.But somehow it is not returning exception.
alice7
+2  A: 

I'm not sure why it doesn't work for you. I created a little sample and it works just fine for me. Take a look at this code:

First I created the code that I want to test.

public interface IXyz
{
    void Foo();
}

public class Xyz : IXyz
{
    public void Foo()
    {
    }
}

public class Sut
{
    public void Bar(IXyz xyz)
    {
        xyz.Foo();
    }
}

Next I'm going to create a test method. In this case I'm using MbUnit but it should work with any unit testing framework.

    [Test]
    [ExpectedException(typeof(ArgumentException), Message = "test string")]
    public void BarFoo_Exception()
    {
        IXyz xyzStub = MockRepository.GenerateStub<IXyz>();
        xyzStub.Stub(x => x.Foo()).Throw(new ArgumentException("test string"));
        new Sut().Bar(xyzStub);
    }

I hope this helps.

Vadim
may be I forgot to add {ExpectedException line on the top of the test].
alice7
A: 

Had the same problem myself. It seems that if the method which you want to throw an exception has parameters then you need to add .IgnoreArguments() before the .Throw(new Exception())

For example, I found that the following would NOT throw the exception:

queue.Stub(x => x.Send(messageQueueTransaction, auditEvent)).Throw(new Exception());

But the following would:

queue.Stub(x => x.Send(messageQueueTransaction, auditEvent)).IgnoreArguments().Throw(new Exception());

Because Vadim's exception-throwing method was parameterless, it worked without ignoring arguments.

Lisa
A: 

Hi,

I had the same issue and I spent few minutes thinking and searching why ...

The solution for me was as the following (C# .NET):

_xyz.Stub(x => x.Function(null)).IgnoreArguments().Throw(new Exception("test string"));

frantisek