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.
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.
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.
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?
The solution for me was as the following:
_xyz.Stub(x => x.Function(null)).IgnoreArguments().Throw(new Exception("test string"));
Note the .IgnoreArguments()
call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With