【发布时间】:2019-10-14 19:44:32
【问题描述】:
我有一个接口定义如下:
public interface TestInterface
{
List<string> TestMethod(List<string> ids);
List<string> TestMethod(List<string> ids, bool testBool);
}
这个接口是由一个名为TestClass的类实现的,但这并不重要。
现在,我有一个单元测试,它执行以下操作:
List<string> testReturnData = GetSomeTestReturnData(); //Not important
Mock<TestInterface> mockedInterface = new Mock<TestInterface>();
mockedInterface.Setup(d => d.TestMethod(It.IsAny<IEnumerable<string>>(), true).Returns(testReturnData);
然后我最终运行单元测试,然后运行一些实际代码,其中使用了上述mockedInterface:
List<string> someValidInput = GetSomeValidInput(); //Not important
// Line causing the exception. testInterfaceInstance is actually the mocked interface
// instance, passed in as a reference
List<string> returnData = testInterfaceInstance.TestMethod(someValidInput, true);
当上面这行代码执行时,立即抛出如下异常:
System.Reflection.TargetParameterCountException:参数计数不匹配。
有人可以解释为什么会这样吗?我提供了有效数量的输入。预期的行为是调用上述应返回前面提到的testReturnData。
在模拟界面设置中,即使我将true替换为It.IsAny<Boolean>(),仍然无法解决问题。
编辑:
其实我发现了这个问题。在模拟设置中,有一个只使用一个输入参数的回调,这让编译器感到困惑。我不认为这很重要,所以我把它省略了:) ...更多细节:实际调用是这样的:
mockedInterface.Setup(d => d.TestMethod(It.IsAny<IEnumerable<string>>(), true).Returns(testReturnData)
.Callback<IEnumerable<string>>(u =>
{
u.ToList();
});
我只需将Callback 更改为:
mockedInterface.Setup(d => d.TestMethod(It.IsAny<IEnumerable<string>>(), true).Returns(testReturnData)
.Callback<IEnumerable<string>, Boolean>((u, v) =>
{
u.ToList();
});
然后测试运行良好。 :)
【问题讨论】:
-
您是否尝试过使用
It.IsAny<List<string>>以使您传入的类型与实际参数类型匹配? (如果你能提供一个minimal reproducible example 以便我们可以轻松地复制它,那真的很有帮助。) -
您是否尝试过重命名
interface的第二种方法?可能Moq在运行时发现了错误的方法? -
谢谢大家,但我找到了问题所在。我在上面的代码中提到了它作为编辑。