Thursday, November 06, 2008

NMock and out parameters

While trying to create a unit test the other day I came across the situation where my mock object needed to return a value via an Out parameter. A quick google turned up this post over at dev:ices.

I thought that had answered all my questions but when I tried it I kept getting a very unhelpful error:

------ Test started: Assembly: Tests.dll ------

TestCase 'Tests.BatchOrderMessageHandlerTests.TestNMock'
failed: NMock2.Internal.ExpectationException : unexpected invocation of foo.DoFoo(<1>, <1>, out)
Expected:
1 time: foo.DoFoo(equal to <1>, equal to <1>, equal to ), will set c=<2>, return <1> [called 0 times]
at NMock2.Mockery.FailUnexpectedInvocation(Invocation invocation)
at NMock2.Mockery.Dispatch(Invocation invocation)
at NMock2.Mockery.MockObject.Invoke(Invocation invocation)
at NMock2.Monitoring.Invoker.Invoke(Invocation invocation)
at NMock2.Monitoring.ProxiedObjectIdentity.Invoke(Invocation invocation)
at NMock2.Monitoring.ProxyInvokableAdapter.Invoke(IMessage msg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Tests.BatchOrderMessageHandlerTests.IFoo.DoFoo(Int32 a, Int32 b, Int32& c)
C:\svn\GLGParnters.TradeIdeas\PositionManager\src\Tests\BatchOrderMessageHandlerTests.cs(136,0): at Tests.BatchOrderMessageHandlerTests.TestNMock()

0 passed, 1 failed, 0 skipped, took 0.77 seconds.



A bit confused I quickly whipped up a trivial test as my unit test was a bit complicated and returned an enum as the Out parameter. My hypothesis was that NMocks couldn't return an enum as an Out parameter.

public interface IFoo
{
int DoFoo(int a, int b, out int c);
}


[Test]
public void TestNMock()
{
IFoo foo = _mockery.NewMock();

Expect.Once.On(foo).Method("DoFoo")
.With(1, 1, Is.Out)
.Will(new SetNamedParameterAction("c", 2), Return.Value(1));

int result = 0;
int a = foo.DoFoo(1, 1, out result);

_mockery.VerifyAllExpectationsHaveBeenMet();
Assert.AreEqual(2, result);
}


This also failed so I checked what version of NMocks I was using. My NMock2.dll assembly had a revision number of 1.0.2313.18049. I downloaded the latest binaries from the NMock website. Checking the version number of the latest build shows it to be 2.0.0.44.

Rerunning the unit tests against this version of the NMock library everything now works!

So, if you're having trouble with out parameters in your NMock mocks, upgrade your build version.

Labels: , ,

0 Comments:

Post a Comment

<< Home