C# 对返回的模拟调用了验证方法

C# 对返回的模拟调用了验证方法,c#,.net,unit-testing,mocking,moq,C#,.net,Unit Testing,Mocking,Moq,我用它来单元测试我的工厂,以及它的产品的后续执行 我有一个ParameterAlgorithmFactory(将计算报表参数的算法返回为IVisibilityParameterAlgorithm)和工厂内的一个方法,该方法对其中的每个参数调用Execute() 为了测试这一点,我编写了如下单元测试: //Verfiy that execute is called on all algorithms produced by factory [TestMethod] public void Para

我用它来单元测试我的工厂,以及它的产品的后续执行

我有一个
ParameterAlgorithmFactory
(将计算报表参数的算法返回为
IVisibilityParameterAlgorithm
)和工厂内的一个方法,该方法对其中的每个参数调用
Execute()

为了测试这一点,我编写了如下单元测试:

//Verfiy that execute is called on all algorithms produced by factory
[TestMethod]
public void ParameterAlgorithmFactory_ReturnedAlgorithm_ExpectExceuteCalled()
{
    var mockFactory = new Mock<IParameterAlgorithmFactory>();
    var parameterAlgorithm = new Mock<IVisibilityParameterAlgorithm>();

    mockFactory.Setup(x => x.Create(LineType.Adjustment)).Returns(parameterAlgorithm.Object);

    new ReportParameters().CreateParameters(new DataSet(), mockFactory.Object);

    parameterAlgorithm.Verify(x=> x.Execute(new DataSet()));
 }
//对工厂生成的所有算法调用execute的Verfiy
[测试方法]
public void参数algorithmfactory_ReturnedAlgorithm_expectExceetCalled()
{
var mockFactory=new Mock();
var parameterAlgorithm=new Mock();
mockFactory.Setup(x=>x.Create(LineType.Adjustment)).Returns(parameterAlgorithm.Object);
新建ReportParameters().CreateParameters(新建DataSet(),mockFactory.Object);
parameterAlgorithm.Verify(x=>x.Execute(newdataset());
}
如您所见,我正在从模拟工厂返回一个模拟算法(
parameterAlgorithm
),然后我想验证调用了
Execute()

然而,我始终得到:

Moq.MockException:预期至少对模拟调用一次,但 从未执行过:x=>x.Execute(新数据集())

即使我可以调试并看到行被
Execute()
ed

也许我在我的工厂里做了太多的工作(返回一个算法并执行它),或者也许我以错误的方式使用Moq


任何关于此测试失败原因的反馈都是值得赞赏的。

正如我在评论中提到的,您应该使用
It.IsAny()
而不是
new DataSet()
作为验证参数


似乎Moq比较的是引用,而不是“类型”,所以最终验证会失败
It.IsAny()
正是如果您只需要一个存根参数,那么应该在这里使用它。

您可能应该使用
It.IsAny()
而不是
new DataSet())
-验证可能对参数使用引用相等,而不是“type”/stub相等。能否提供
ReportParameters.CreateParameters
的详细信息?你确定用
LineType.Adjustment
作为参数调用
Create
吗?@PatrykĆwiek-看起来
It.IsAny()
已经完成了这项任务!我会仔细阅读这方面的内容,以便将来理解和使用。如果你想写下来作为答案,我会接受。@m.edmondson Done!:)