Mocking IEnumerable and IEnumerator with NMock2

Edit: This post is actually about a weird NMock error message. As Nigel Thorne so kindly pointed out, this way of testing an IEnumerable is kind of awkward and cumbersome, as I should have just done something like this:

Please use this approach, unless your test subject is actually the implementation of the foreach construct ๐Ÿ˜‰

Original post:
A recent problem I had was when I attempted to mock a function returning an IEnumerable<T>. I went about and punched in somthing that I expected to work – something like this:

– and then I set some expectations on the usage:

– and the usage inside my class under test was something like this:

– but then I ran the test, and I got this cryptic error message:

This was really annoying! Especially due to the fact that the foreach prevented me from seeing what was actually going on. It took me a few minutes to realize that the error came from me being too sloppy to check out the IEnumerator interface I was mocking – the interface looks like this:

(where the generic IEnumerator<T> interface inherits from IEnumerator, narrowing the return type of the Current property down to objects of type T).

Can you spot the error?

The return type of MoveNext is bool!!!

When I am mocking a method call like this:

NMock will check the method signature – and if the signature has a return type other than void, NMock tries to be nice and – instead of emitting an error (which IMO would be appropriate) – returns null! And since null is a reference type, but the expected type was bool, I got the cryptic RemotingException.

The solution was obvious:

PS: I am posting this to avoid having this problem again (for too long). I remember having had this error before, but it took me almost 30 minutes to realize what was wrong. Hopefully, next time I will remember ๐Ÿ™‚