One of the great benefits of using mocks in your tests is being able to check how your classes behave when exceptions are thrown.  You do test for this sort of thing, right? :-)

Let’s say we have a persistence mechanism that talks to SQL.  What happens when we get a SQL primary key violation?  What if we are talking to web services and the connection drops or we get some other WCF exception?  How do we handle that?

More importantly, how do we get Rhino Mocks, Moq or NSubstitute to raise those exceptions.  Let’s have a look.

Rhino Mocks

[Fact]
public void Rhino_throwing_exceptions()
{
var monkey = MockRepository.GenerateMock<IMonkey>();
monkey.Stub(m => m.Name).Throw(new ApplicationException());
Assert.Throws<ApplicationException>(() => monkey.Name);
}

This is pretty simple code.  Instead of returning a value, just throw an exception when the method is called.  Too easy!

Moq

[Fact]
public void Moq_throwing_exceptions()
{
var monkey = new Mock<IMonkey>();
monkey.Setup(m => m.Name).Throws(new ApplicationException());
Assert.Throws<ApplicationException>(() => monkey.Object.Name);
}

The Moq code is much the same as the Rhino code, except we still have that .Object. tax that annoys me so much.

NSubstitute

[Fact]
public void Nsub_throwing_exceptions()
{
var monkey = Substitute.For<IMonkey>();
monkey.Name.Returns(args => { throw new ApplicationException(); });
Assert.Throws<ApplicationException>(() => monkey.Name);
}

Not quite as clean as the other two frameworks here, though I’m sure the guys will rectify this soon enough.

 

And the winner: Rhino Mocks. Even though Moq requires slightly less code than Rhino it’s .Object. distinctions will always annoy me.

 

Other posts in this series: