使用Moq模拟功能构造函数参数,并验证它是否被调用两次 [英] Using Moq to Mock a Func<> constructor parameter and Verify it was called twice
问题描述
从本文中提出问题(如何进行仿制),并进行了改编作为答案是不正确的.
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<IFooBarProxy> __fooBarProxyFactory;
public FooBar(Func<IFooBarProxy> fooBarProxyFactory)
{
_fooBarProxyFactory = fooBarProxyFactory;
}
public void Process()
{
_fooBarProxyFactory();
_fooBarProxyFactory();
}
}
我需要模拟作为构造函数参数传递的Func<>,该函数断言该函数被调用了两次.
I have a need to mock a Func<> that is passed as a constructor parameter, the assert that the func was call twice.
尝试模拟函数var funcMock = new Mock<Func<IFooBarProxy>>();
时,由于Func类型不可模拟,因此Moq会引发异常.
When trying to mock the function var funcMock = new Mock<Func<IFooBarProxy>>();
Moq raises and exception as the Func type is not mockable.
问题在于,如果不模拟函子,就无法验证函子被调用了(n)次. funcMock.Verify( (), Times.AtLeast(2));
The issue is that without mocking the func it is not possible to verify that the func was called (n) times. funcMock.Verify( (), Times.AtLeast(2));
推荐答案
我认为没有必要对Func使用模拟.
I don't think it is necessary to use a mock for the Func.
您可以简单地自己创建一个普通的Func,该函数返回IFooBarProxy
的模拟:
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);
这篇关于使用Moq模拟功能构造函数参数,并验证它是否被调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!