How to throw exception in new rhino mocks 3.5

alice7 picture alice7 · Jan 5, 2010 · Viewed 14.1k times · Source

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.

Answer

Vadim picture Vadim · Jan 6, 2010

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.