Test ‐ TestContainer - dnwls16071/Backend_Study_TIL GitHub Wiki
- 테스트에서 도커 컨테이너를 실행할 수 있는 라이브러리
- 테스트 실행시 DB를 설정하거나 별도의 프로그램 또는 스크립트를 실행할 필요가 없다.
- 보다 Production에 가까운 테스트를 만들 수 있으나 테스트 실행 속도가 느려진다는 단점이 있다.
📚 TestContainer 기능
// https://mvnrepository.com/artifact/org.testcontainers/testcontainers
testImplementation group: 'org.testcontainers', name: 'testcontainers', version: '1.21.2'
@TestContainers
: JUnit5 확장팩으로 테스트 클래스에 @Container를 사용한 필드를 찾아서 컨테이너 라이프 사이클 관련 메서드를 실행해준다.
@Container
: 인스턴스 필드에 사용하면 모든 테스트마다 컨테이너를 재시작하고, static 필드에 사용하면 클래스 내부 모든 테스트에서 동일한 컨테이너를 재사용한다.
@Testcontainers
@ExtendWith(MockitoExtension.class)
class StudyServiceTest {
@Mock
protected StudyRepository studyRepository;
@Mock
protected MemberService memberService;
@Container
static GenericContainer postgreSQLContainer = new GenericContainer("postgres:latest")
.withEnv("POSTGRES_DB", "studytest")
.withEnv("POSTGRES_PASSWORD", "testpass")
.withExposedPorts(5432);
// ...
}
}
public ComposeContainer environment = new ComposeContainer(
new File("src/test/resources/composev2/compose-test.yml")
)
.withExposedService("redis-1", REDIS_PORT)
.withExposedService("db-1", 3306);
- YAML로 관리하는 도커 컴포즈 파일을 위와 같이 관리를 할 수 있다.