Out parameters with RhinoMocks

Jason Buxton picture Jason Buxton · Sep 26, 2011 · Viewed 8.1k times · Source

I'm obviously confused - this is a task I've accomplished with several other frameworks we're considering (NMock, Moq, FakeItEasy). I have a function call I'd like to stub. The function call has an out parameter (an object).

The function call is in a use case that is called multiple times within the code. The calling code hands in parameters, including a NULL object for the out parameter. I'd like to set up an expected OUT parameter, based on the other parameters provided.

How can I specify an expected INBOUND out parameter of NULL, and an expected OUTBOUND out parameter of an object populated the way I expect it? I've tried it six ways to Sunday, and so far haven't been able to get anything back but NULL for my OUTBOUND out parameter.

Answer

Phil Sandler picture Phil Sandler · Sep 26, 2011

From http://ayende.com/wiki/Rhino+Mocks+3.5.ashx#OutandRefarguments:

Ref and out arguments are special, because you also have to make the compiler happy. The keywords ref and out are mandantory, and you need a field as argument. Arg won't let you down:

User user;
if (stubUserRepository.TryGetValue("Ayende", out user))
{
  //...
}
stubUserRepository.Stub(x =>
  x.TryGetValue(
    Arg.Is("Ayende"), 
    out Arg<User>.Out(new User()).Dummy))
  .Return(true);

out is mandantory for the compiler. Arg.Out(new User()) is the important part for us, it specifies that the out argument should return new User(). Dummy is just a field of the specified type User, to make the compiler happy.