无缘无故地"Parameter count mismatch"



我有一个接口定义如下:

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

在模拟界面设置中,即使我用It.IsAny<Boolean>()替换true,它仍然不能解决问题。

编辑:

实际上我想通了这个问题。在模拟设置中,有一个回调只使用一个输入参数,这让编译器感到困惑。我认为这并不重要,所以我把它省略:)......更多细节:实际调用是这样的:

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();
});

然后测试运行良好。:)

我认为您的代码示例缺少一些东西。你从你的模拟中得到了.Object吗?

根据您的代码,我可以生成这个,这不会抛出:

using System.Collections.Generic;
using Moq;
using Xunit;
namespace XUnitTestProject1
{
public interface TestInterface
{
List<string> TestMethod(List<string> ids);
List<string> TestMethod(List<string> ids, bool testBool);
}

public class UnitTest1
{
[Fact]
public void Foo()
{
List<string> testReturnData = new List<string>();
Mock<TestInterface> mockedInterface = new Mock<TestInterface>();
mockedInterface
.Setup(d => d.TestMethod(It.IsAny<List<string>>(), true)).Returns(testReturnData);
List<string> someValidInput = new List<string>();
var testInterfaceInstance = mockedInterface.Object;
List<string> returnData = testInterfaceInstance.TestMethod(someValidInput, true);
}
}
}

这是使用xUnit作为测试运行程序。

最新更新