NMock Out Parameters

I’ve often thought that NMock is under-documented. The way I’ve started to learn how to use this extremely useful library is through the well-formatted examples that Ian has left around. Practical examples often show you far more than a glossary of terms or a list of available methods.

This week Andy and Drew were wanting to test a method which had both a return value and an out parameter. A quick look through the NMock Quickstart, Tutorial, Advanced or Cheat Sheet pages didn’t show any way of achieving this. Thankfully the Blogosphere came through once again to prove that you can do this with NMock.

Say you have a method in your mockable class called:

public string AddGreeting(string userName)

you could expect to write a Stub declaration such as

.Will(Return.Value("Hello World"));

If your method has an out parameter as well, such as:

public string AddGreeting(string userName, out int characterCount)

then your Stub declaration will need to look like this:

string expectedUserName = "World";
.With(Is.EqualTo(expectedUserName), Is.Out)
.Will(new SetNamedParameterAction(["characterCount", 11), Return.Value("Hello World"));

The Is.Out is setting the expectation that one of the parameters you’re specifying is an Out parameter. The SetNamedParameterAction object is undocumented and has been found using reflection. This is a useful feature which hasn’t been documented. The NMock project appears to being built using continuous integration these days but that obviously doesn’t happen with the project documentation.
[Edited to update code sample to make use of Is.EqualTo() and explicitly declared variables for any non-out parameters in the method call. 18th Feb 2009]

Making a Mockery

Thanks to some example code by Ian I’ve completed my first Mockery. NMock allows you to instantiate mock objects based on interface declarations alone.
It’s already saved me a potential chicken and egg scenario where to get an instance of the normal object that’s inputting into the method I was testing I’d have had to include a project which relied on the one I was in the midst of building. Compilers tend to hate the chicken and egg question and usually go on strike.
So, NMock to the rescue and I must say it took no time at all to get up to speed with. Yes, it did require me to set all of the properties on the object that were being used, rather than relying on defaults created by Constructor methods. However, accurately controlling the data retrieved from the object is such a benefit. It will no doubt save the time spent where tests at the moment retrieve data from a database.