pbg0205 / BE-tutorials

BE-tutorials 🧑‍💻
0 stars 0 forks source link

테스트 컨테이너 학습하기 #2

Open pbg0205 opened 1 year ago

pbg0205 commented 1 year ago

참고 내용

pbg0205 commented 1 year ago

test container reference : https://www.testcontainers.org/

1. 테스트 컨테이너의 편리한 경우

  1. 데이터 엑세스 계층 통합 테스트
    • 운영과 동일한 상태로 개발 가능
    • 간단한 설정을 통한 컨테이너 생성 가능
  2. 애플리케이션 통합 테스트
    • 다양한 의존성 있는 컴포넌트(e.g. RDB, MQ) 를 편리하게 테스트해볼 수 있음
  3. UI/ 승인 테스트
    • 자동화된 UI 테스트 가능(Selenium 과 호환 가능?)


테스트 컨테이너의 단점


JDBC 를 사용한다면 간단히 설정 가능

spring:
  datasource:
    url: jdbc:tc:mysql:8:///soolsul?TC_REUSABLE=true
    username: test
    password: test121212
    driver-class-name: org.testcontainers.jdbc.ContainerDatabaseDriver


Redis의 경우, 별도로 만들어줘야 함.

public abstract class TestRedisContainer {

    private static final String DOCKER_REDIS_IMAGE = "redis:7.0.5-alpine";

    public static GenericContainer REDIS_CONTAINER =
            new GenericContainer<>(DockerImageName.parse(DOCKER_REDIS_IMAGE))
                    .withExposedPorts(6379)
                    .withReuse(true);

    static {
        REDIS_CONTAINER.start();

        System.setProperty("spring.redis.host", REDIS_CONTAINER.getHost());
        System.setProperty("spring.redis.port", REDIS_CONTAINER.getMappedPort(6379).toString());
    }
}
pbg0205 commented 1 year ago

https://www.testcontainers.org/quickstart/junit_5_quickstart/

JUnit 5 Quickstart

1. 테스트 컨테이너가 없을 떄의 문제점

local installation 환경의 문제점 image


1. Add Testcontainers as a test-scoped dependency

testImplementation "org.junit.jupiter:junit-jupiter:5.8.1"
testImplementation "org.testcontainers:testcontainers:1.17.6"
testImplementation "org.testcontainers:junit-jupiter:1.17.6"


2. Get Testcontainers to run a Redis container during our tests

@Container
public GenericContainer redis = new GenericContainer(DockerImageName.parse("redis:5.0.3-alpine"))
    .withExposedPorts(6379);


테스트 실행 시 TestContainer 는 아래와 같은 로그를 보여준다.


3. Make sure our code can talk to the container

@Testcontainers
public class RedisBackedCacheIntTest {

    private RedisBackedCache underTest;

    // container {
    @Container
    public GenericContainer redis = new GenericContainer(DockerImageName.parse("redis:5.0.3-alpine"))
        .withExposedPorts(6379);

    // }

    @BeforeEach
    public void setUp() {
        String address = redis.getHost();
        Integer port = redis.getFirstMappedPort();

        // Now we have an address and port for Redis, no matter where it is running
        underTest = new RedisBackedCache(address, port);
    }

    @Test
    public void testSimplePutAndGet() {
        underTest.put("test", "example");

        String retrieved = underTest.get("test");
        assertThat(retrieved).isEqualTo("example");
    }
}
pbg0205 commented 1 year ago

사이드 리뷰 피드백

1. @DynamicPropertySource(참고 레퍼런스 : https://recordsoflife.tistory.com/607)