MockRestServiceServer:如何用一个身体来模拟一个POST调用?

2022-09-01 23:42:13

我正在尝试通过以下方式模拟POST方法:MockRestServiceServer

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

问题:如何在此设置中验证请求正文?

我浏览了文档和一些示例,但仍然无法弄清楚如何做到这一点。


答案 1

您可以使用 content().string 来验证正文:

.andExpect(content().string(expectedContent))

content().bytes

this.mockServer.expect(content().bytes(“foo”.getBytes()))

this.mockServer.expect(content().string(“foo”))


答案 2

我怎么会做这样的测试。我希望在模拟服务器上以格式接收正确的正文,如果已收到此正文,服务器将使用格式的正确响应正文进行响应。当我收到响应正文时,我会将其映射到 POJO 并检查所有字段。另外,我会在发送之前将请求从映射到POJO。因此,现在我们可以检查映射是否在两个方向上工作,并且可以发送请求并解析响应。代码将如下所示:StringStringString

  @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(""));
  }

推荐