Using wiremock, can I return a body that is dependent on the post request

后端 未结 6 841
盖世英雄少女心
盖世英雄少女心 2021-02-12 20:10

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

6条回答
  •  无人共我
    2021-02-12 20:57

    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)));
    

提交回复
热议问题