2017년 6월 25일 일요일

spring integration test

You can implement Integration test by using spring boot starter test.
As default, You can implement each layer test as controller, service, repository
,however, sometimes integration test is needed to check all the work folw is working fine.
At that time, by random or defined port, spring test can be proceeded.

For example, when you use 3rd party server, external cache, database,
usually these server and modules are mocked by Junit.
However, if 3rd party server's response or real vaue of external cache, database are changed,
all the service can be working as not expected.
To protect like that cases, and check the service is working as you expected,
You can set the integration test.

Since spring-boot-starter-test already made the function like this,
you can implement these test by using just some annotations.

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\" }");
    }
}

By declaring @RunWith and @SpringBootTest, this test class proceed the test with the server executed by random port.

In this example, I used http://www.mocky.io, and set the response as "hello world", did a test.

This test is done by RANDOM_PORT like below, you can find the test is succeed.

2017-06-25 17:39:55.028  INFO 15388 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 5343 (http)

All example can be downloaded by the link as below.

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

댓글 없음 :

댓글 쓰기