开发者

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

开发者 https://www.devze.com 2022-12-12 08:51 出处:网络
I am using Moq - but could easily swap to another mock framework if needed. I have a interface defined:

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 SetClientCallbackSende开发者_如何学Cr from my unit test?

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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消