Moq + Unit Testing - System.Reflection.TargetParameterCountException: Parameter count mismatch
I'm tring to use a lambda with a multiple-params function but Moq throws this exception at runtime when I attempt to call the mock.Object.Convert(value, null, null, null);
line.
System.Reflection.TargetParameterCountException: Parameter count mismatch
The code is:
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);
What is the proper way to implement it?
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:
[TestMethod]
public void IValueConverter()
{
var myStub = new Mock<IValueConverter>();
myStub.Setup(conv => conv.Convert(It.IsAny<object>(), It.IsAny<Type>(), It.IsAny<object>(), It.IsAny<CultureInfo>())).
Returns((object one, Type two, object three, CultureInfo four) => (int)one + 5);
var value = 5;
var expected = 10;
var actual = myStub.Object.Convert(value, null, null, null);
Assert.AreEqual<int>(expected, (int) actual);
}
No exceptions, test passed.
Not an answer for OP but perhaps for future googlers:
I had a Callback
that didn't match the signature of the method being setup
Mock
.Setup(r => r.GetNextCustomerNumber(It.IsAny<int>()))
.Returns(AccountCounter++)
.Callback<string, int>(badStringParam, leadingDigit =>
{
// Doing stuff here, note that the 'GetNextCustomerNumber' signature is a single int
// but the callback unreasonably expects an additional string parameter.
});
This was the result of some refactoring and the refactoring tool of course couldn't realise that the Callback
signature was incorrect