Search code examples
c#.netmoqrhino-mocks

Replacement Rhino Mocks GetArgumentsForCallsMadeOn() for Moq Callback() not receiving original arguments


I am trying to replace this Rhino Mocks implementation:

private bool IsHandshakeCalled()
{
    var args = httpExecutorBuilderStub.GetArgumentsForCallsMadeOn(st => st.ExecuteHttpWebRequestAndReturn(
        Arg<HttpMethod>.Is.Anything, Arg<string>.Is.Anything, Arg<string>.Is.Anything));

    if (args.Count > 0)
    {
        return args[0][0].Equals(HttpMethod.POST) &&
               args[0][1].Equals("/api/v2/connection/command") &&
               args[0][2].Equals(JsonConvert.SerializeObject(new HandshakeRequestDto(500)));
    }
    return false;
}

with the following Moq implementation:

private bool IsHandshakeCalled()
{
    HttpMethod? capturedHttp = null;
    string? capturedString1 = null;
    string? capturedString2 = null;

    httpExecutorBuilderStub.Setup(st => st.ExecuteHttpWebRequestAndReturn(
        It.IsAny<HttpMethod>(), It.IsAny<string>(), It.IsAny<string>()))
        .Callback<HttpMethod, string, string>((h, s1, s2) => {
            capturedHttp = h;
            capturedString1 = s1;
            capturedString2 = s2;
        });

    if (capturedHttp != null)
    {
        return capturedHttp.Equals(HttpMethod.POST) &&
            capturedString1.Equals("/api/v2/connection/command") &&
            capturedString2.Equals(JsonConvert.SerializeObject(new HandshakeRequestDto(500)));
    }
    return false;
}

The problem is, my Moq implementation is not receiving original arguments.

Probably I have some issues with Moq's Callback() method.

  • What do I do wrong?
  • Should I use some different Moq method?

Solution

  • The problem was in setup-ing the mock in the wrong place. I had to move it to another method so it is setup-ed sooner.