Moq Callback() 的替换 Rhino Mocks GetArgumentsForCallsMadeOn() 未收到原始参数

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

我正在尝试替换这个 Rhino Mocks 实现:

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

使用以下最小起订量实施:

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

问题是,我的 Moq 实现没有收到原始参数。

可能我对 Moq 的 Callback() 方法有一些问题。

有一个叫做Capture.In的built-in功能,它可以将所有方法调用的参数保存到集合中。

例如:

//Arrange
const string inputString = "ThisWillHandled";
var args = new List<string>();
mockedHandler.Setup(handler => handler.Handle(Capture.In(args)));

var SUT = new SUT(mockedHandler.Object);

//Act
SUT.TheAction(inputString);

//Assert
Assert.AreEqual(args.Count, 1);
Assert.AreEqual(args.First(), inputString);


将此模式应用到您的代码中,它看起来像这样:

private bool IsHandshakeCalled()
{
    //Arrange
    var capturedHttps  = new List<HttpMethod>();
    var capturedStrings1 = new List<string>();
    var capturedStrings2 = new List<string>;

    httpExecutorBuilderStub.Setup(st => st.ExecuteHttpWebRequestAndReturn(
            Capture.In(capturedHttps), Capture.In(capturedStrings1), Capture.In(capturedStrings2)));

    //Act
    //Call the stub via the SUT

    //Assert
    if (capturedHttps.Count == 1)
    {
        return capturedHttps.Single().Equals(HttpMethod.POST) &&
               capturedStrings1.Single().Equals("/api/v2/connection/command") &&
               capturedStrings2.Single().Equals(JsonConvert.SerializeObject(new HandshakeRequestDto(500)));
    }
    return false;
}

在尝试检查捕获的参数之前,请确保您正在通过 SUT 调用存根的 ExecuteHttpWebRequestAndReturn 方法。

问题出在 setup-ing 模拟的错误位置。我不得不将其移至另一种方法,因此 setup-ed 更快。