我试图以以下方式模拟使用MockRestServiceServer的POST方法:
MockRestServiceServer server = bindTo(restTemplate).build();
server.expect(requestTo("/my-api"))
.andExpect(method(POST))
.andRespond(withSuccess(expectedResponce, APPLICATION_JSON));问题:如何在此设置中验证请求体?
我浏览了文献资料和一些示例,但仍然不知道如何做到这一点。
发布于 2019-08-05 07:25:21
您可以使用内容().string验证主体:
.andExpect(content().string(expectedContent))
this.mockServer.expect(content().bytes("foo".getBytes())) this.mockServer.expect(content().string("foo"))
发布于 2019-08-06 15:34:25
我会怎么做这样的测试。我希望在模拟的服务器上以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(""));
}发布于 2019-08-12 07:13:40
可以使用HttpMessageConverter可以帮助。根据文档,HttpMessage转换器::read方法可以是提供检查输入能力的地方。
https://stackoverflow.com/questions/57328602
复制相似问题