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