Testcontainers 支持使用 DockerComposeContainer 类开箱即用地启动 Docker Compose。在创建此类的实例时,您必须公开所有容器:
@Testcontainers
public class DockerComposeTest {
@Container
public static DockerComposeContainer<?> environment =
new DockerComposeContainer<>(new File("docker-compose.yml"))
.withExposedService("database_1", 5432, Wait.forListeningPort())
.withExposedService("keycloak_1", 8080,
Wait.forHttp("/auth").forStatusCode(200)
.withStartupTimeout(Duration.ofSeconds(30)));
@Test
void dockerComposeTest() {
System.out.println(environment.getServicePort("database_1", 5432));
System.out.println(environment.getServicePort("keycloak_1", 8080));
}
}
上面的示例将 PostgreSQL 数据库和 Keycloak 映射到您机器上的随机临时端口。等待检查通过后,您的测试将立即运行,您可以使用 .getServicePort() 访问实际端口。
WebClient 配置的一个可能解决方案是使用ApplicationContextInitializer,因为您必须在容器启动之前以某种方式定义 Spring Boot 属性:
public class PropertyInitializer
implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
// static access to environment variable of the test
TestPropertyValues
.of("your_web_client_base_url=http://localhost:" + environment.getServicePort("serviceC", 8080) + "/api")
.applyTo(configurableApplicationContext);
}
}
然后您可以使用以下方法为您的集成测试注册初始化程序:
@Testcontainers
@ContextConfiguration(initializers = {PropertyInitializer.class})
class DockerComposeTest {
}
作为替代方案,您也可以尝试仅模拟与外部服务with WireMock 的所有 HTTP 通信。