Verifying a delegate was called with Moq

后端 未结 4 1322
隐瞒了意图╮
隐瞒了意图╮ 2021-02-11 14:20

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

4条回答
  •  萌比男神i
    2021-02-11 14:34

    Moq does not support mocking delegates. But you can create some interface, with method, which matches your delegate signature:

    public interface IBar
    {
        void M(int number);
    }
    

    Then create mock, which implements this interface, and use this mock object to create delegate:

    Mock bar = new Mock();
    Foo foo = new Foo(bar.Object.M); 
    A a = new A(foo);
    bar.Verify(x => x.M(5));   
    

    After exercising your sut, you will be able to verify expectations on your mocked object.

    UPDATE: Actually you can simply pass bar.Object.M to your sut, without Foo delegate instance creation. But anyway, mocking delegates requires interface creation.

提交回复
热议问题