views:

37

answers:

2

I am using Moq - but could easily swap to another mock framework if needed.

I have a interface defined:

public interface IBaseEngineManagerImp
{
   void SetClientCallbackSender(IClientCallbackSender clientCallbackSender);
}

I then mock IBaseEngineManagerImp with

mockEngineManagerImp = new Mock<IEngineManagerImp>();
EngineManager engineManager = new EngineManager(mockEngineManagerImp.Object);

engineManager then calls SetClientCallbackSender passing in a value.

How do I get the value that was passed to SetClientCallbackSender from my unit test?

(I wish to call some methods on clientCallbackSender as part of the test)

+3  A: 

you can use the .Callback method on the mock, to call any function on the parameter that was passed in to the SetClientCallbackSender method:

mockEngineManagerImp.Setup(x => x.SetClientCallbackSender(It.IsAny<IClientCallbackSender>()))
            .Callback((IClientCallbackSender c) => c.DoSomething());
Mark Heath
+1  A: 

In rhino, you use WhenCalled or GetArgumentsForCallsmadeOn:

Thingy argument;
mock
  .Stub(x => x.SetClientCallbackSender(Arg<IClientCallbackSender>.Is.Anything))
  .WhenCalled(call => argument = (Thingy)call.Arguments[0]);
// act
//...
// assert
Assert.AreEqual(7, argument.X);

The problem with this implementation is, that you just get the latest argument. You could put more control to this by using argument contraints (instead of Is.Anything).

or

// act
//...
// assert
Thingy argument = 
  (Thingy)mock
    .GetArgumentsFormCalsMadeOn(x => x.SetClientCallbackSender(
      Arg<IClientCallbackSender>.Is.Anything))[0][0];

The problem with the GetArgumentsFormCalsMadeOn is, that it returns a two dimensional array, a row for each call and a column for each argument. So you have to know exactly how many calls your unit under test performs.

Stefan Steinegger