12

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.

Jason Buxton
  • 153
  • 1
  • 8

3 Answers3

22

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.

Phil Sandler
  • 27,544
  • 21
  • 86
  • 147
6

In case using repository to generate Mock/Stub

checkUser = MockRepository.GenerateMock<ICheckUser>

You can setup expectation with out parameter

checkUser
.Expect(c => c.TryGetValue(Arg.Is("Ayende"), out Arg<User>.Out(new User()).Dummy)
.Return(true) 
Bhavesh
  • 293
  • 4
  • 10
6

This solution is cleaner and works fine with Rhino Mocks 3.6:

myStub.Stub(x => x.TryGet("Key", out myValue))
      .OutRef("value for the out param")
      .Return(true);
Marcelo Oliveira
  • 653
  • 5
  • 16
  • This is the only way that worked for me. It wouldn't recognize the `out Arg.Out` syntax. +1 – inejwstine Aug 17 '20 at 23:26
  • I would also add that as of C# 7.0, you can use an underscore as a discard for the `out` variable, simplifying it further to `x.TryGet("Key", out _)` (which also saves you from having to declare `myValue` elsewhere). – inejwstine Aug 17 '20 at 23:29