WireMock.Net 如何响应有时出现错误而其他情况正常

WireMock.Net How to response sometimes an error and others OK

我正在使用 WireMock.Net,我想使用相同的 URI 配置 Wiremock,它有时 returns OK(200) 有时错误响应 (500)。我见过的例子总是 returning 相同的状态码,例如:

WireMockServer.Given(Request.Create().WithPath("/some/thing").UsingGet())
    .RespondWith(
        Response.Create()
            .WithStatusCode(200)
            .WithBody("Hello world!"));

我如何模拟例如:return OK (200) 偶数请求和 return Internal-Server-Error (500) 奇数请求。我也想回应不同的身体。

一段时间后,在查看 WireMock 存储库时,我找到了一种方法。这只是一个示例(这不是您可以编写的最佳代码):

WireMockServer.Given(Request.Create().WithPath("/some/thing").UsingPost())
                .RespondWith(new CustomResponse());

CustomResponse 实施 IResponseProvider:

public class CustomResponse : IResponseProvider
{
    private static int _count = 0;
    public Task<(ResponseMessage Message, IMapping Mapping)> ProvideResponseAsync(RequestMessage requestMessage, IWireMockServerSettings settings)
    {
        ResponseMessage response;
        if (_count % 2 == 0)
        {
            response = new ResponseMessage() { StatusCode = 200 };
            SetBody(response, @"{ ""msg"": ""Hello from wiremock!"" }");
        }
        else
        {
            response = new ResponseMessage() { StatusCode = 500 };
            SetBody(response, @"{ ""msg"": ""Hello some error from wiremock!"" }");
        }

        _count++;
        (ResponseMessage, IMapping) tuple = (response, null);
        return Task.FromResult(tuple);
    }

    private void SetBody(ResponseMessage response, string body)
    {
        response.BodyDestination = BodyDestinationFormat.SameAsSource;
        response.BodyData = new BodyData
        {
            Encoding = Encoding.UTF8,
            DetectedBodyType = BodyType.String,
            BodyAsString = body
        };
    }
}

如果您总是希望交替响应,您可以只使用 simple scenario

WireMockServer.Given(Request.Create()
    .WithPath("/some/thing")
    .UsingGet())
    .InScenario("MyScenario")
    .WhenStateIs("Started")
    .WillSetStateTo("Something")
    .RespondWith(
        Response.Create()
            .WithStatusCode(200)
            .WithBody("Hello world!"));
WireMockServer.Given(Request.Create()
    .WithPath("/some/thing")
    .UsingGet())
    .InScenario("MyScenario")
    .WhenStateIs("Something")
    .WillSetStateTo("Started")
    .RespondWith(
        Response.Create()
            .WithStatusCode(500)
            .WithBody("Error"));