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

爱⌒轻易说出口 提交于 2019-11-30 17:01:22

I don't think it is necessary to use a mock for the Func.

You can simply create an ordinary Func yourself that returns a mock of IFooBarProxy:

int numberOfCalls = 0;
Func<IFooBarProxy> func = () => { ++numberOfCalls;
                                  return new Mock<IFooBarProxy>(); };

var sut = new FooBar(func);

sut.Process();

Assert.Equal(2, numberOfCalls);

As of at least Moq 4.5.28, you can mock and verify the Func as you would expect to be able to. I couldn't tell when this feature was added (according to the original question at some point this did not work).

[Test]
public void TestFoobar()
{
    var funcMock = new Mock<Func<IFooBarProxy>>();
    var fooBar = new FooBar(funcMock.Object);
    fooBar.Process();
    funcMock.Verify(x => x(), Times.AtLeast(2));
}

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<Func<IFooBarProxy>>();.

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<IFooBarTestMethods>();
testMethodsMock
    .Setup(x => x.FooBarProxyFactory())
    .Returns(new Mock<IFooBarProxy>());

var sut = new FooBar(testMethodsMock.Object.FooBarProxyFactory);
testMethodsMock.Verify(x => x.FooBarProxyFactory(), Times.Exactly(2));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!