-
@SpringBootTest 에서 RestTemplate 으로 localhost 를 호출할 때카테고리 없음 2023. 2. 19. 15:14
SpringBoot Application에서 원격 API의 샘플 API를 만들고 Test 로 비지니스 테스트를 하려고 합니다. 하지만 Connection refuse. 에러가 발생합니다. 아래는 에러가 나는 샘플 코드 입니다.
@SpringBootTest public class TmpTest { @Autowired RestTemplate restTemplate; @Test void call() { String res = restTemplate.getForObject("http://localhost:8080/test", String.class); Assertions.assertNotNull(res); } }
해결 방법은 여러가지가 있겠지만 가장 간단한 방법은 아래와 같습니다.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) public class TmpTest { @Autowired RestTemplate restTemplate; @Test void call() { String res = restTemplate.getForObject("http://localhost:8080/test", String.class); Assertions.assertNotNull(res); } }
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT
WebEnvironment 에 대해서 알아봅니다.
- 기본은 MOCK 이고 실제 WebApplicationContext 를 띄우지 않습니다. mock WebApplicationContext 를 사용합니다.
- RANDOM_PORT 는 랜덤포트로 WebApplicationContext 를 만듭니다. - 포트 충돌 해결
- DEFINED_PORT 는 설정된 포트로 만들고요. - 서버포트를 사용해야 할 때, 포트 충돌 가능성 있음.
- NONE 는 Web 관련 세팅을 하지 않습니다. - 테스트 속도를 빠르게 만들 때