Open pbg0205 opened 1 year ago
test container reference : https://www.testcontainers.org/
spring:
datasource:
url: jdbc:tc:mysql:8:///soolsul?TC_REUSABLE=true
username: test
password: test121212
driver-class-name: org.testcontainers.jdbc.ContainerDatabaseDriver
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());
}
}
https://www.testcontainers.org/quickstart/junit_5_quickstart/
local installation 환경의 문제점
testImplementation "org.junit.jupiter:junit-jupiter:5.8.1"
testImplementation "org.testcontainers:testcontainers:1.17.6"
testImplementation "org.testcontainers:junit-jupiter:1.17.6"
@Container
public GenericContainer redis = new GenericContainer(DockerImageName.parse("redis:5.0.3-alpine"))
.withExposedPorts(6379);
테스트 실행 시 TestContainer 는 아래와 같은 로그를 보여준다.
getHost()
메서드를 사용하자. localhost의 경우 일부 환경에서만 동작하기 때문에 다른 환경에서 동작하지 않을 수 있음(e.g. CI 환경)@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");
}
}
Dynamic PropertyRegistry.add(String, Supplier
@SpringBootTest
@Testcontainers
public class ArticleLiveTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:11")
.withDatabaseName("prop")
.withUsername("postgres")
.withPassword("pass")
.withExposedPorts(5432);
@DynamicPropertySource
static void registerPgProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url",
() -> String.format("jdbc:postgresql://localhost:%d/prop", postgres.getFirstMappedPort()));
registry.add("spring.datasource.username", () -> "postgres");
registry.add("spring.datasource.password", () -> "pass");
}
// tests are same as before
}
참고 내용