Thursday, April 10, 2008

NMock2 RemotingException

Test method XyzUnitTest.TestSomething threw exception: System.Runtime.Remoting.RemotingException: ByRef value type parameter cannot be null.

It turns out that this is caused by not having a return value in the expectation when returning a primitive:

The line of tested code that was failing:

int id = this.Foo.GetId(arg1, arg2, arg3);

The expectation that was causing the failure in the test code was:
Expect.AtMost(1).On(foo).Method("GetId").WithAnyArguments();

Need to be changed to:
Expect.AtMost(1).On(foo).Method("GetId").WithAnyArguments().Will(Return.Value(Id));

I think this is especially important as a (non nullable) int is being returned so the proxy is treating it as byref, hence it can not be null. This may have been missed if it was returning a object as a null object can be returned in this scenario.

3 comments:

Unknown said...
This comment has been removed by the author.
Unknown said...

for some reason that import part has been clipped.
It is supposed to read:
The expectation that was causing the failure in the test code was:
Expect.AtMost(1).On(foo)
.Method("GetId")
.WithAnyArguments();

Need to be changed to:
Expect.AtMost(1).On(foo)
.Method("GetId")
.WithAnyArguments()
.Will(Return.Value(Id));

Anonymous said...

I assume you use the RC from nmock.org.

If you give the V1.0 from https://sourceforge.net/projects/nmock2/
a chance then you will see that missing return values will cause a much user friendlier exception, pointing you directly to where you missed it.