IT/TDD & Test
RestClientTest를 알아보자~
데모버전
2021. 3. 27. 10:32
반응형
- RestClientTest 어노테이션은 외부 API를 사용할 때 대상 API를 MOCKING 할 수 있는 유용한 테스트이다.
- 요청을 받는 쪽이 아닌 요청을 하는 쪽 입장에서의 테스트이다.
- @RestClientTest를 사용하면 MockRestServiceServer라는 임시 서버를 Bean으로 생성해준다.
- @SpringBootTest와 달리 지정한 최소한의 Context만 사용해서 테스트를 진행한다.
- 아래는 기존 Service 코드이다.
@Service
public class RestClientTestService {
private final RestTemplate restTemplate;
private final String openApiUrl = "https://httpbin.org/get";
public RestClientTestService(RestTemplateBuilder restTemplateBuilder){
this.restTemplate = restTemplateBuilder.build();
}
public Rest getApi() {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(openApiUrl)
.queryParam("a", "a");
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
httpHeaders.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
HttpEntity<?> httpEntity = new HttpEntity<>(httpHeaders);
return restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, Rest.class).getBody();
}
}
- 위 서비스 코드에 대한 RestClientTest를 작성해보면 아래와 같이 작성할 수 있다.
@RunWith(SpringRunner.class)
@RestClientTest(value = RestClientTestService.class)
public class RestClientTestServiceTest {
@Autowired
RestClientTestService restClientTestService;
@Autowired
private MockRestServiceServer mockServer;
private final String openApiUrl = "https://httpbin.org/get";
@Test
public void getApi(){
// given
Rest rest = new Rest();
Args args = new Args();
args.setA("a");
rest.setArgs(args);
String expect = "{\"args\":{\"a\":\"a\"},\"headers\":{\"Accept\":\"application/json\",\"Content-Type\":\"application/json\",\"Host\":\"httpbin.org\",\"User-Agent\":\"Java/11.0.7\",\"X-Amzn-Trace-Id\":\"Root=1-605defad-35b5c60e6d4e616220bfffb0\"},\"origin\":\"14.47.104.108\",\"url\":\"https://httpbin.org/get?a=a\"}";
mockServer.expect(requestTo(openApiUrl + "?a=a"))
.andRespond(withSuccess(expect, MediaType.APPLICATION_JSON));
// when
Rest api = restClientTestService.getApi();
// then
assertThat(api.getArgs().getA()).isEqualTo(rest.getArgs().getA());
}
}
참고 사이트
REST test test...
Method GET POST OPTIONS PUT DELETE HEAD
resttesttest.com
Spring Boot test annotation - 머루의개발블로그
오늘 이시간에는 Spring boot의 Test annotation 들을 살펴볼 예정이다. Spring boot 에서는 Test도 쉽게 할 수 있도록 많이 지원해주고 있다. 예전에 Spring Boot 1.4 Test에 보면 필자가 남긴 Spring boot 1.4에 추가
wonwoo.ml
Spring Boot에서 외부 API 테스트하기
안녕하세요? 이번 시간엔 Spring Boot의 @RestClientTest 예제를 진행해보려고 합니다. 모든 코드는 Github에 있기 때문에 함께 보시면 더 이해하기 쉬우실 것 같습니다. 1. 문제 상황 예를 들어 외부 API를
jojoldu.tistory.com
반응형