WireMock.Net 如何响应有时错误和其他 OK

问题描述

我正在使用 wiremock.Net,我想使用相同的 URI 配置 wiremock,它有时返回 OK(200),有时返回 Error Response(500)。我见过的例子总是返回相同的状态代码,例如:

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

例如,我如何模拟:对偶数请求返回 OK (200),对奇数请求返回 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

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