3

I'm working with WireMock.Net, and I want to configure Wiremock with the same URI, it sometimes returns OK(200) and sometimes Error Response(500). The examples I've seen is always returning the same status code, for example:

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

How can I simulate for example: return OK (200) on an even request and return Internal-Server-Error (500) on an odd request. I want to respond differents bodys as well.

urmat abdykerimov
  • 427
  • 1
  • 7
  • 17
satellite satellite
  • 893
  • 2
  • 10
  • 27

2 Answers2

4

After a while, and looking in WireMock repo, I found a way to do it. This is just an example (it is not the best code you can write):

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

CustomResponse Implements 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
        };
    }
}
satellite satellite
  • 893
  • 2
  • 10
  • 27
0

If you always wanted the responses to alternate, you could just use a 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"));
agoff
  • 5,818
  • 1
  • 7
  • 20