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
Stub.On(mockObject) .Method(AddGreeting) .With("World") .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"; Stub.On(mockObject) .Method(AddGreeting) .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]