起订量 +单元测试 - System.Reflection.TargetParameterCountException:参数计数不匹配
我尝试使用带有多个参数函数的 lambda,但当我尝试调用 mock.Object.Convert(value, null, null, null);
行时,Moq 在运行时抛出此异常。
System.Reflection.TargetParameterCountException: Parameter count mismatch
代码是:
var mock = new Mock<IValueConverter>();
mock.Setup(conv => conv.Convert(It.IsAny<Object>(), It.IsAny<Type>(),
It.IsAny<Object>(), It.IsAny<CultureInfo>())).Returns((Int32 num) => num + 5);
var value = 5;
var expected = 10;
var actual = mock.Object.Convert(value, null, null, null);
实现它的正确方法是什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是您的
Returns
子句。您正在设置一个 4 参数方法,但仅使用 1 参数 lambda。我运行以下命令没有问题:没有异常,测试通过。
It's your
Returns
clause. You have a 4 parameter method that you're setting up, but you're only using a 1 parameter lambda. I ran the following without issue:No exceptions, test passed.
这不是OP的答案,但也许是未来的googlers的答案:
我有一个
Callback
,它与正在设置的方法的签名不匹配这是一些重构的结果,重构工具当然不能意识到
Callback
签名不正确Not an answer for OP but perhaps for future googlers:
I had a
Callback
that didn't match the signature of the method being setupThis was the result of some refactoring and the refactoring tool of course couldn't realise that the
Callback
signature was incorrect也许是因为您传递的是
null
但It.IsAny
这只是我在黑暗中的一刺,我更熟悉Rhino.Mocks。
我的第二个猜测:
查看了下载附带的 Moq.chm 后,
您正在使用
Setup(Expression>)
方法,该方法“为模拟类型指定设置”对void
方法的调用。”您需要
Setup(Expression>)
方法“为调用值返回方法指定模拟类型的设置”。所以你可以尝试:
Perhaps it's because you are passing
null
butIt.IsAny<Object>()
is expecting anyobject
exceptnull
? What happens if you do the following?:This is just a stab in the dark from me, I'm more familiar with Rhino.Mocks.
My 2nd guess:
Having looked at the Moq.chm that comes with the download,
You are using the
Setup(Expression<Action<T>>)
method which "Specifies a setup on the mocked type for a call to avoid
method."You want te
Setup<TResult>(Expression<Func<T,TResult>>)
method that "Specifies a setup on the mocked type for a call to a value returning method".So you could try:
就我而言,我认为
Returns
中的类型是输出类型,但实际上它是输入类型。因此,如果您有一个方法,
正确的子句是
.Returns(...)
,而不是.Returns(...)
这是我最初是这么想的。我的错误是因为我最初测试的是具有相同输入和返回类型的函数 - 例如
public virtual string Foo(string a)
。In my case, I thought that the type in
Returns<>
is the output type, but in fact it was the input type(s).So if you have a method
The correct clause is
.Returns<int, int>(...)
, NOT.Returns<string>(...)
which is what I thought initially.My mistake was because I was testing a function with the same input and return type initially - for example
public virtual string Foo(string a)
.