How to find the value that has been passed to a method on my mocked (Moq or Rhino Mocks) interface?

StackOverflow https://stackoverflow.com/questions/1802580

Question

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)

Was it helpful?

Solution

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());

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top