如何断言一个动作被调用

时间:2011-06-20 14:46:11

标签: c# tdd rhino-mocks

我需要资产一个由模拟组件调用的动作。

 public interface IDispatcher
    {
     void Invoke(Action action);
    }

    public interface IDialogService
    {
      void Prompt(string message);
    }

    public class MyClass
    {
    private readonly IDispatcher dispatcher;
    private readonly IDialogservice dialogService;
    public MyClass(IDispatcher dispatcher, IDialogService dialogService)
    {
     this.dispatcher = dispatcher;
    this.dialogService = dialogService;
    }

    public void PromptOnUiThread(string message)
    {
     dispatcher.Invoke(()=>dialogService.Prompt(message));
    }
    }

    ..and in my test..

   [TestFixture]
    public class Test
    {
     private IDispatcher mockDispatcher;
     private IDialogService mockDialogService;
    [Setup]
    public void Setup()
    {
     mockDispatcher = MockRepository.GenerateMock<IDispatcher>();
     mockDialogService = MockRepository.GenerateMock<IDialogService>();
    }

    [Test]
    public void Mytest()
    {
     var sut = CreateSut();
    sut.Prompt("message");

    //Need to assert that mockdispatcher.Invoke was called
    //Need to assert that mockDialogService.Prompt("message") was called.
    }
     public MyClass CreateSut()
    {
      return new MyClass(mockDipatcher,mockDialogService);
    }
    }

也许我需要重新构建代码,但对此感到困惑。你能告诉我吗?

2 个答案:

答案 0 :(得分:7)

您实际上正在测试这行代码:

dispatcher.Invoke(() => dialogService.Prompt(message));

您的类调用mock来调用另一个mock上的方法。这通常很简单,您只需要确保使用正确的参数调用Invoke。不幸的是,这个论点是一个lambda并不容易评估。但幸运的是,它是对模拟的调用,这使得它再次变得容易:只需调用它并验证另一个模拟被调用:

Action givenAction = null;
mockDipatcher
  .AssertWasCalled(x => x.Invoke(Arg<Action>.Is.Anything))
  // get the argument passed. There are other solutions to achive the same
  .WhenCalled(call => givenAction = (Action)call.Arguments[0]);

// evaluate if the given action is a call to the mocked DialogService   
// by calling it and verify that the mock had been called:
givenAction.Invoke();
mockDialogService.AssertWasCalled(x => x.Prompt(message));

答案 1 :(得分:3)

首先需要对模拟进行预期。例如,我想测试Invoke只被调用一次而且我不关心传入的参数。

mockDispatcher.Expect(m => m.Invoke(null)).IgnoreArguments().Repeat.Once();

然后你必须断言并验证你的期望

mockDispatcher.VerifyAllExpectations();

你可以用同样的方式为第二个模拟做,但是每单元测试有两个模拟是不好的做法。你应该在不同的测试中测试每一个。

如需设定期望,请阅读http://ayende.com/wiki/Rhino+Mocks+Documentation.ashx