MockRestServiceServer: 본문으로 POST 콜을 모의하는 방법
POST 방식을 조롱하려고 합니다.MockRestServiceServer다음과 같은 방법으로 합니다.
MockRestServiceServer server = bindTo(restTemplate).build();
server.expect(requestTo("/my-api"))
.andExpect(method(POST))
.andRespond(withSuccess(expectedResponce, APPLICATION_JSON));
문제:이 설정에서 요청 본문을 확인하려면 어떻게 해야 합니까?
문서와 몇 가지 예를 훑어봤지만 아직 어떻게 해야 할지 모르겠어요.
content().string을 사용하여 본문을 확인할 수 있습니다.
.andExpect(content().string(expected Content))
이 . mock Server . expect ( content() . bytes ( " foo " . get Bytes ) )
this.mockServer.expect(content().string("foo"))
내가 어떻게 그런 테스트를 할 수 있을까.조롱된 서버에서 적절한 본문을 수신할 것으로 예상합니다.String이 바디가 수신되면 서버는 적절한 응답 바디를 사용하여 응답합니다.String포맷합니다.응답 본문을 받으면 POJO에 매핑하여 모든 필드를 확인합니다.또한, 저는 요청서를 작성하겠습니다.StringPOJO에 송신합니다.이제 매핑이 양방향으로 작동하는지 확인하고 요청을 전송하거나 응답을 구문 분석할 수 있습니다.코드는 다음과 같습니다.
@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 메서드는 입력 기능을 체크하는 장소가 될 수 있습니다.
언급URL : https://stackoverflow.com/questions/57328602/mockrestserviceserver-how-to-mock-a-post-call-with-a-body
'programing' 카테고리의 다른 글
| 중력 형태의 js 오차 (0) | 2023.03.20 |
|---|---|
| onclick은 새 반응 구성요소를 렌더링하지 않습니다. (0) | 2023.03.20 |
| Angular와 ASP의 혼합.NET MVC/Web API? (0) | 2023.03.20 |
| Angular 8 - 느린 모듈 로딩: 오류 TS1323: '--module' 플래그가 'commonjs' 또는 'esNext'인 경우에만 동적 가져오기가 지원됩니다. (0) | 2023.03.20 |
| 'npm start'는 "프로젝트 종속성 트리에 문제가 있을 수 있습니다."라는 오류를 반환합니다. (0) | 2023.03.20 |