如何断言一个动作被调用

Mik*_*ike 3 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);
    }
    }
Run Code Online (Sandbox Code Playgroud)

也许我需要重构代码,但对此感到困惑.您能否提一些建议?

Ste*_*ger 7

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

dispatcher.Invoke(() => dialogService.Prompt(message));
Run Code Online (Sandbox Code Playgroud)

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

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));
Run Code Online (Sandbox Code Playgroud)