1

I provide a generic provider for Json serialization:

public interface IJsonSerializerProvider
{   
    T? Deserialize<T>(string value);

    string Serialize(object? obj);

    object? Deserialize(string value, string type);    
}

public class JsonSerializerProvider : IJsonSerializerProvider
{ ... }

On my tests, I provide a mocked version of this one which proxying real provider as default feature like this:

  object? paramObj = null;

  JsonSerializerProviderMock
  .Setup(x => x.Serialize(IsAny<object?>()))
  .Callback<object?>(s =>
  {
      paramObj = s;
  })
  .Returns<object?>(x => new JsonSerializerProvider().Serialize(paramObj));

   var param1 = "";
   var param2 = "";

   JsonSerializerProviderMock
  .Setup(x => x.Deserialize<IsAnyType>(IsAny<string>()))
  .Callback<string>(s =>
  {
      param1 = s;
  })
  .Returns<IsAnyType>(x => new JsonSerializerProvider().Deserialize<IsAnyType>(param1));

   JsonSerializerProviderMock
  .Setup(x => x.Deserialize(IsAny<string>(), IsAny<string>()))
  .Callback<string, string>((s, r) =>
  {
      param1 = s;
      param2 = r;
  })
  .Returns<object?>(x => new JsonSerializerProvider().Deserialize(param1, param2));

Unfortunately, I got this error at startup for the last definition:

System.ArgumentException
Invalid callback. Setup on method with 2 parameter(s) cannot invoke callback with different  number of parameters (1).
   at Moq.MethodCall.ValidateNumberOfCallbackParameters(Delegate callback, MethodInfo callbackMethod)
3
  • 1
    Are you sure that doing all that configuring is simpler and easier to read than just creating a regular class for mocking? And for what purpose do you want to insert a proxy? Commented Oct 8 at 9:58
  • Try replacing <IsAnyType> with the actual type your test uses (e.g. string). Commented Oct 8 at 10:47
  • 2
    My wetware compiler can't compile the example. Please edit the question so that it provides a minimal, reproducible example. Commented Oct 8 at 10:53

1 Answer 1

0

the issue was on the Returns as it is having a wrong signature.

below code should work.

 object? paramObj = null;
 Mock<IJsonSerializerProvider> JsonSerializerProviderMock = new Mock<IJsonSerializerProvider>();

 var param1 = "";
 var param2 = "";

 JsonSerializerProviderMock
.Setup(x => x.Deserialize(IsAny<string>(), IsAny<string>()))
.Callback<string, string>((s, r) =>
{
    param1 = s;
    param2 = r;
})
.Returns(new JsonSerializerProvider().Deserialize(param1, param2));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.