MockrestServiceserver:如何用body嘲笑帖子呼叫



我试图以MockRestServiceServer模拟帖子方法:

MockRestServiceServer server = bindTo(restTemplate).build();
server.expect(requestTo("/my-api"))
        .andExpect(method(POST))
        .andRespond(withSuccess(expectedResponce, APPLICATION_JSON));

问题:如何在此设置中验证请求主体?

我浏览了文档和一些示例,但仍然无法弄清楚如何完成。

您可以使用content((。字符串验证身体:

.andexpect(content((。字符串(endure fordiencontent((

或content((。字节:

this.mockserver.expect(content((。字节(" foo; getBytes((((

this.mockserver.expect(content((。字符串(; foo; quot; quot; quot((

我将如何进行这种测试。我希望在模拟的服务器上以String格式接收适当的主体,如果收到了该主体,则服务器将以String格式的适当响应主体做出响应。当我收到响应主体时,我会将其映射到Pojo并检查所有字段。另外,在发送之前,我将String的请求映射到POJO。因此,现在我们可以检查映射是否可以在两个方向上工作,并且可以发送请求和解析响应。代码将是这样的:

  @Test
  public void test() throws Exception{
    RestTemplate restTemplate = new RestTemplate();
    URL testRequestFileUrl = this.getClass().getClassLoader().getResource("post_request.json");
    URL testResponseFileUrl = this.getClass().getClassLoader().getResource("post_response.json");
    byte[] requestJson = Files.readAllBytes(Paths.get(Objects.requireNonNull(testRequestFileUrl).toURI()));
    byte[] responseJson = Files.readAllBytes(Paths.get(Objects.requireNonNull(testResponseFileUrl).toURI()));
    MockRestServiceServer server = bindTo(restTemplate).build();
    server.expect(requestTo("http://localhost/my-api"))
          .andExpect(method(POST))
          .andExpect(content().json(new String(requestJson, "UTF-8")))
          .andRespond(withSuccess(responseJson, APPLICATION_JSON));
    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl("http://localhost/my-api");
    ObjectMapper objectMapper = new ObjectMapper();
    EntityOfTheRequest body = objectMapper.readValue(requestJson, EntityOfTheRequest.class);
    RequestEntity.BodyBuilder bodyBuilder = RequestEntity.method(HttpMethod.POST, uriBuilder.build().toUri());
    bodyBuilder.accept(MediaType.APPLICATION_JSON);
    bodyBuilder.contentType(MediaType.APPLICATION_JSON);
    RequestEntity<EntityOfTheRequest> requestEntity = bodyBuilder.body(body);
    ResponseEntity<EntityOfTheResponse> responseEntity = restTemplate.exchange(requestEntity, new ParameterizedTypeReference<EntityOfTheResponse>() {});
    assertThat(responseEntity.getBody().getProperty1(), is(""));
    assertThat(responseEntity.getBody().getProperty2(), is(""));
    assertThat(responseEntity.getBody().getProperty3(), is(""));
  }

可以使用httpmessageconverter可以提供帮助。根据文档,httpmessageconverter :: read方法可以是提供输入能力的地方。

最新更新