2017년 6월 25일 일요일

spring integration test 설정

스프링 부트 테스트 스타터를 통해서 integration test를 실행할 수 있다.
기본적으로 Junit을 통해 각각의 controller, service, repository의 개별 테스트를 진행할 수 있는데,
전체적으로 해당 동작이 정상적으로 동작하는지 integration test를 해야할 경우가 있다.
그와 같은 경우에, spring에서 random 혹은 defined된 port로 서버를 실행하여 실제 테스트를 진행할 수 있다.

예를 들면, 3rd party 서버를 사용하거나 외부 cache, DB 등을 사용하는 서버의 경우, 보통 Junit을 통해 해당 서버와 모듈을 mocking하여 테스트를 진행한다.
하지만, 3rd party 서버의 응답이 변경되거나, cache, db 등의 실제 값이 바뀐 경우, 전체 서비스가 정상적으로 동작하지 않을 수 있다.
그와 같은 경우를 막고, 실제 정상적으로 동작 가능한지 테스트하기 위해 integration test를 설정할 수 있다.

spring boot starter 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를 선언함으로써, 해당 테스트 클래스는 랜덤으로 서버를 실행하여 실제 서버와 같이 동작하며 테스트를 진행한다.

해당 예제에서는 http://www.mocky.io를 사용해 hello world 를 응답받도록 설정하고, 테스트를 진행하였다.

아래와 같이 RANDOM_PORT로 해당 테스트는 실행되고, 성공하는 것을 확인할 수 있다.

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

댓글 없음 :

댓글 쓰기