Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw exception in new rhino mocks 3.5

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.

like image 202
alice7 Avatar asked Jan 05 '10 17:01

alice7


4 Answers

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.

like image 132
Vadim Avatar answered Nov 13 '22 14:11

Vadim


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.

like image 40
Lisa Avatar answered Nov 13 '22 16:11

Lisa


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?

like image 43
Phil Sandler Avatar answered Nov 13 '22 14:11

Phil Sandler


The solution for me was as the following:

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

Note the .IgnoreArguments() call.

like image 1
frantisek Avatar answered Nov 13 '22 15:11

frantisek