TestContainer 초기 설정 및 기능 설명


TestContainer 기능

자바 코드로 docker image를 띄우는 Junit 의 기능이라 생각하면 된다.

즉, 자바 코드로 구현하는 docker compose라 생각하면 된다.

TestContainer 사용 이유

redis를 단위 테스트를 하기 위해서 여러가지 방안을 찾아봤다. 일단 지금 현재 프로젝트가 H2로 embeded test로 진행됐으니 embended redis가 있는지 찾아봤다.

https://github.com/ozimov/embedded-redis

embeded redis 를 지원하는 오픈소스가 존재했고 실제로 이렇게 적용한 사례들도 몇몇 있었지만 블로그나 다른 의견에서 오류 점이 많이 있다하는 말도 있었고 무엇보다 마지막 commit이 4년전이라 내키지 않게 됐다.

embeded redis를 사용하는거에 대한 부정적인 블로그 참고자료

스프링 Redis 테스트 환경 구축하기 (Embedded Redis, TestContainer) — devoong2 (tistory.com)

Spring에서 Redis Test 하기 — 기러기는 기록기록 (tistory.com)

TestContainer 초기 설정

    // test-containers
    testImplementation "org.testcontainers:testcontainers:1.19.0"
    testImplementation "org.testcontainers:junit-jupiter:1.19.0"

image.png

@Configuration
public class RedisConfig {

	private static final String REDIS_IMAGE = "redis:7.0.8-alpine";
	private static final int REDIS_PORT = 6379;  // 기본 포트로 변경
	private static final GenericContainer<?> REDIS_CONTAINER = new GenericContainer<>(REDIS_IMAGE)
		.withExposedPorts(REDIS_PORT)
		.withReuse(true);

	static {
		REDIS_CONTAINER.start();
	}

	@Bean
	public LettuceConnectionFactory redisConnectionFactory() {
		RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(
			REDIS_CONTAINER.getHost(), REDIS_CONTAINER.getMappedPort(REDIS_PORT)
		);
		return new LettuceConnectionFactory(configuration);
	}
}