Spring integration test

13 March 2018

spring boot starter test 라이브러리를 통해, integration test를 진행하는 법을 알아보도록 하겠습니다.

보통 controller, service, repository 등의 layer에 대한 테스트를 진행할 수 있는데,
때때로는 전체 workflow 테스트를 위해서 integration test를 진행해야 하는 경우가 생깁니다.

그러한 경우에, random port를 통해 spring test를 진행할 수 있습니다.

예를 들어, 3rd party 서버나 외부 캐쉬, 데이타베이스 등을 사용할 때 이러한 모듈은 junit에 의해 mock으로 선언됩니다.
하지만, 3rd party 서버의 응답이나 외부 캐시의 실제 값, 데이터베이스가 변경되었을 경우 전체 서비스의 정상 동작 역시 보장이 되어야 합니다.
그러한 경우에 대한 테스트를 위해 integration test를 진행하게 됩니다.

spring-boot-starter-test 라이브러리는 이미 다양한 기능을 제공하기 때문에,
간단히 annotation 선언을 통해 아래와 같이 test를 진행할 수 있습니다.

package org.blog.test.integration;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.test.context.junit4.SpringRunner;

import static org.assertj.core.api.Assertions.assertThat;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class IntegrationTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void getStringTest() {
        HttpEntity response = this.restTemplate.exchange("/test", HttpMethod.GET, null, String.class);
        assertThat(response.getBody()).isEqualTo("{ \"hello\": \"world\" }");
    }
}
@Runwith 어노테이션과 @SpringBootTest 어노테이션을 선언함으로써, 해당 test는 random port로 서버가 실행되면서 진행되게 됩니다.

이 예제에서는 우리는 http://www.mocky.io 를 사용해, 테스트 이전에 설정된 값인 "hello world"가 정상적으로 응답되는지 체크를 할 것입니다.

테스트를 실행한 이후, 아래와 같이 정상적으로 테스트가 통과된 것을 확인할 수 있습니다.

2017-06-25 17:39:55.028  INFO 15388 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 5343 (http)
전체 예제는 아래에서 다운로드 받을 수 있습니다.

https://gitlab.com/shashaka/integration-test-project