테스트 컨테이너는 데이터베이스, 메세지 브로커, 웹 브라우저 등을 실행 가능한 도커 컨테이너로 제공해주는 오픈소스 프레임워크 입니다.
Java, Go, .Net, Node.js, Python, Rust 등 다양한 언어에서 사용할 수 있습니다.
운영환경과 비슷한 조건에서 테스트를 수행하고자 하는 경우 필요한 리소스들을 설정해야 하는데 TestContainers를 사용하면 손쉽게 설정할 수 있습니다.
Mysql 8.0 기준으로 작성했습니다.
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.testcontainers:junit-jupiter'
runtimeOnly 'mysql:mysql-connector-java:8.0.32'
testImplementation "org.testcontainers:mysql:1.19.8"
testImplementation 'org.springframework.boot:spring-boot-testcontainers'
testImplementation 'org.testcontainers:junit-jupiter'
}
또는
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.testcontainers:junit-jupiter'
runtimeOnly 'mysql:mysql-connector-java:8.0.32'
testImplementation 'org.testcontainers:mysql:1.19.8'
testImplementation 'org.testcontainers:testcontainers:1.19.8'
testImplementation 'org.testcontainers:junit-jupiter:1.19.8'
}
// Test code
@DataJpaTest
@Testcontainers
public class Test {
...
}
TestContainer를 사용해 mysql을 이용할 test class에 @Testcontainers를 명시해 해당 test가 TestContainer에 의해 관리되게 합니다.
application.yml
# application.yml
spring:
datasource:
url: jdbc:tc:mysql:8.0.32:///test
driver-class-name: org.testcontainers.jdbc.ContainerDatabaseDriver
Test Code에서는 위에서 보았던 대로 class에 @TestContainer만 추가해주면 됩니다.