Verifying a delegate was called with Moq

后端 未结 3 2033
忘掉有多难
忘掉有多难 2021-02-11 14:19

i got a class that gets by argument a delegate. This class invokes that delegate, and i want to unit test it with Moq. how do i verify that this method was called ?

exam

相关标签:
3条回答
  • 2021-02-11 14:34

    You can do something like that:

     public interface IWithFOOMethod
     {
         void FooAlikeMethod(int number);
     }
    
     Mock<IWithFOOMethod> myMock = new Mock<IWithFOOMethod>();
    
     A a = new A(myMock.Object.FooAlikeMethod);
    
     myMock.Verify(call => call.Foo(It.IsAny<int>()), Times.Once())
    
    0 讨论(0)
  • 2021-02-11 14:50

    What about using an anonymous function? It can act like an inline mock here, you don't need a mocking framework.

    bool isDelegateCalled = false;
    var a = new A(a => { isDelegateCalled = true});
    
    //do something
    Assert.True(isDelegateCalled);
    
    0 讨论(0)
  • 2021-02-11 14:55

    As of this commit Moq now supports the mocking of delegates, for your situation you would do it like so:

    var fooMock = new Mock<Foo>();
    var a = new A(fooMock.Object);
    

    Then you can verify the delegate was invoked:

    fooMock.Verify(f => f(5), Times.Once);
    

    Or:

    fooMock.Verify(f => f(It.IsAny<int>()), Times.Once);
    
    0 讨论(0)
提交回复
热议问题