我正在使用WireMock.Net,我想用相同的URI配置Wiremock,它有时返回OK(200),有时返回错误响应(500)。我见过的示例总是返回相同的状态码,例如:
WireMockServer.Given(Request.Create().WithPath("/some/thing").UsingGet())
.RespondWith(
Response.Create()
.WithStatusCode(200)
.WithBody("Hello world!"));例如,我如何模拟:在偶数请求上返回OK (200),在奇数请求上返回Internal-Server-Error (500)。我也想回应不同的身体。
发布于 2021-07-23 09:10:00
过了一段时间,我查看了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
};
}
}发布于 2021-07-24 01:26:06
如果你总是想让响应交替,你可以只使用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"));https://stackoverflow.com/questions/68492138
复制相似问题