Using Moq to Mock a Func<> constructor parameter and Verify it was called twice

前端 未结 3 598
萌比男神i
萌比男神i 2021-01-03 18:59

Taken the question from this article (How to moq a Func) and adapted it as the answer is not correct.

public class FooBar
{
    private Func

        
3条回答
  •  太阳男子
    2021-01-03 19:20

    Since Moq v4.1.1308.2120

    As of this version, which was released some months after this question was asked (Aug 21, 2013), the functionality to mock a Func<> has been added. So with any current version of mock, you can use var funcMock = new Mock>();.

    Original (outdated) answer

    If you have a lot of callback Func's, Actions, etc, it's better to define a helper interface in your tests and mock that interface. This way you can use the regular Moq functionality, like setting up return values, testing input arguments, etc.

    interface IFooBarTestMethods
    {
        IFooBarProxy FooBarProxyFactory();
    }
    

    Usage

    var testMethodsMock = new Mock();
    testMethodsMock
        .Setup(x => x.FooBarProxyFactory())
        .Returns(new Mock());
    
    var sut = new FooBar(testMethodsMock.Object.FooBarProxyFactory);
    testMethodsMock.Verify(x => x.FooBarProxyFactory(), Times.Exactly(2));
    

提交回复
热议问题