by Rob
20. March 2010 15:55
I'm a big fan of Rhino Mocks. I've been using it regularly over the past year or two. But I always seem to be finding new functionality. The latest came about from a conversation with a colleague. They wanted to assert that multiple calls were made to a method. This is a common scenario and can be tested by using the following syntax.
sut.AssertWasCalled(thing => thing.DoSomething(Arg<int>.Is.Anything), options => options.Repeat.Times(4));
But the requirement went further to say that they needed to check that for the three calls that were made they each passed a specific ID. After a little research we came across GetArgumentsForCallsMadeOn method. This allows you to access the parameters of each call to the method on your mocked object. Here's some code to show how this works:
[TestClass]
public class when_i_call_something_twice_i_can_take_a_look_at_both_arguements : context_base
{
protected override IThing create_sut()
{
return MockRepository.GenerateStub<IThing>();
}
protected override void because()
{
sut.DoSomething(15);
sut.DoSomething(20);
}
[TestMethod]
public void should_tell_me_that_arg_one_is_15()
{
sut.GetArgumentsForCallsMadeOn(thing => thing.DoSomething(Arg<int>.Is.Anything))[0][0].should_be_equal_to(15);
}
[TestMethod]
public void should_tell_me_that_arg_two_is_20()
{
sut.GetArgumentsForCallsMadeOn(thing => thing.DoSomething(Arg<int>.Is.Anything))[1][0].should_be_equal_to(20);
}
}
The indexer [0][0] refers to the [first method call][first argument] and then in the second test [second method call][first argument]. Some of the syntactic sugar in this example comes from JP Boodhoo’s BDD library.