How to assert that an action was called

前端 未结 2 1486
不思量自难忘°
不思量自难忘° 2021-01-20 21:13

I need to asset an action called by a mock component.

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

    public interface IDial         


        
2条回答
  •  长发绾君心
    2021-01-20 22:10

    You are actually testing this line of code:

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

    Your class calls the mock to invoke a method on another mock. This is normally simple, you just need to make sure that Invoke is called with the correct arguments. Unfortunately, the argument is a lambda and not so easy to evaluate. But fortunately, it is a call to the mock which makes it easy again: just call it and verify that the other mock had been called:

    Action givenAction = null;
    mockDipatcher
      .AssertWasCalled(x => x.Invoke(Arg.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));
    

提交回复
热议问题