Out parameters with RhinoMocks
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.
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.
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)
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);
精彩评论