Tuesday, June 17, 2008

Mocking Generic Method with NMock2 (part2)

Well although this feature has been mentioned on the web it doesn't seen to exist in any version of NMock2 I can find. With a bit of digging I worked out how to implement it myself.

You can download the assembly from NMock2Extensions try it out, or download the source from svn.

Here's an example of using it...


Stub.On(childScope)
.Method(new GenericMethodMatcher("Get", typeof(IControl)))
.Will(Return.Value(control));

Expect.Once.On(childScope)
.Method(new GenericMethodMatcher("Get",typeof(IDocument)))
.Will(Return.Value(NewMock()));


As you can see, you can Stub or Mock on the same method with different generic types and they are handled differently, as you would expect.

Happy Mocking

1 comment:

Anonymous said...

The feature for mocking generic methods with type parameter matchers is included in the version of NMock2 v 1.0 at http://sourceforge.net/projects/nmock2.

This version is the continued development of the nmock v2.0 (nmock.org).

Yes confusing but the way it is at the moment.

Happy mocking
Urs

GitHub Projects