使用wiremock,我可以返回一个依赖于post请求的主体 [英] Using wiremock, can I return a body that is dependent on the post request
问题描述
我正在尝试测试openid提供程序类。 openid消费者类正在发出http请求。我正在使用wiremock模拟对此请求的响应。我试图模拟一个有效的openid响应。但是,有效响应取决于请求参数。使用wiremock,我可以设置一个模拟请求,其中响应的主体依赖于请求参数吗?
I am trying to test an openid provider class. The openid consumer class is making an http request. I am mocking the response to this request using wiremock. I am trying to mock a valid openid response. However, the valid response depends on the request parameters. Using wiremock, can I set up a mock request where the body of the response is dependent on the request parameters?
推荐答案
这是可能,你只需要使用ResponseTansformer。在下面的示例代码中,responseDefinition由下面给出的存根确定。在这里,我通过简单地将主体字节返回给调用者来模拟编码服务。虽然在变换器中我可以根据请求的内容自由返回任何我喜欢的内容。
This is possible, you just have to make use of a ResponseTansformer. In the below example code the responseDefinition is determined by the stubbing given below. Here I mock an encoding service by simply returning the body bytes back to the caller. Although in the transformer I am free to return whatever I like based on the contents of the request.
int port = 8080;
WireMockServer wireMockServer = new WireMockServer(new WireMockConfiguration().port(port).extensions(new ResponseTransformer() {
@Override
public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, FileSource files) {
return new ResponseDefinitionBuilder().like(responseDefinition)
.withBody(request.getBodyAsString().getBytes())
.build();
}
@Override
public String name() {
return "request body returning request transformer";
}
}));
wireMockServer.start();
WireMock.configureFor("localhost", port);
stubFor(post(urlEqualTo("/encode"))
.willReturn(aResponse()
.withHeader("Content-Type", "application/octet-stream")
.withStatus(200)));
stubFor(post(urlEqualTo("/decode"))
.willReturn(aResponse()
.withHeader("Content-Type", "application/octet-stream")
.withStatus(200)));
这篇关于使用wiremock,我可以返回一个依赖于post请求的主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!