【发布时间】:2020-09-22 14:08:59
【问题描述】:
我正在使用 Spring Boot 并在 Testcontainers 中运行测试。
有时(在开发时)我不想针对测试容器运行测试,而是针对已经运行的容器。
有没有办法根据 Spring 配置文件、环境变量等禁用测试容器?
现在我正在评论容器注入代码并定期检查它们。
【问题讨论】:
标签: java spring-boot junit5 testcontainers
我正在使用 Spring Boot 并在 Testcontainers 中运行测试。
有时(在开发时)我不想针对测试容器运行测试,而是针对已经运行的容器。
有没有办法根据 Spring 配置文件、环境变量等禁用测试容器?
现在我正在评论容器注入代码并定期检查它们。
【问题讨论】:
标签: java spring-boot junit5 testcontainers
是的,可以使用配置文件来完成。
一种可能的解决方案是(这个想法是使用static 关键字并假设使用.withLocalCompose(true)):
@Configuration
@Profile("test")
public class TestDockerConfig {
// initialize your containers in static fields/static block
}
并在需要时使用测试配置文件。即使您在所有测试中都导入了该配置,也应该只为“测试”的配置加载。
我们的想法是提供 docker 环境来测试套件和使用属性配置文件。 它可以:
由于启动容器需要时间,因此您只想以静态方式执行一次,它将在所有类之前加载。
希望对您有所帮助。
【讨论】:
按照 Sergei 的推荐 https://github.com/testcontainers/testcontainers-java/issues/2833#event-3405411419
这是解决方案:
public class FixedHostPortGenericDisableableContainer<T extends FixedHostPortGenericDisableableContainer<T>> extends FixedHostPortGenericContainer<T> {
private boolean isActive;
public FixedHostPortGenericDisableableContainer(@NotNull String dockerImageName) {
super(dockerImageName);
}
@Override
public void start() {
if (isActive) {
super.start();
}
}
public FixedHostPortGenericDisableableContainer isActive(boolean isActive) {
this.isActive = isActive;
return this;
}
}
用法
// set this environment variable to true to disable test containers
public static final String ENV_DISABLE_TEST_CONTAIENRS = "DISABLE_TEST_CONTAIENRS";
@Container
private static GenericContainer dynamoDb =
new FixedHostPortGenericDisableableContainer("amazon/dynamodb-local:1.11.477")
.isActive(StringUtils.isBlank(System.getenv(ENV_DISABLE_TEST_CONTAIENRS)))
.withFixedExposedPort(8001, 8000)
.withStartupAttempts(100);
【讨论】:
根据the docs,在测试中获取容器的一种方法是使用 JDBC URL。这使您可以轻松地在例如基于配置文件的测试容器和本地主机:
application-integration.yml
spring.datasource.url: jdbc:tc:postgresql:12-alpine:///mydatabase
application-dev.yml
spring.datasource.url: jdbc:postgresql://localhost:5432/mydatabase
如文档所述:
- TC 需要在运行时位于应用程序的类路径中才能正常工作
- 对于 Spring Boot(2.3.0 之前的版本),您需要手动指定驱动程序
spring.datasource.driver-class-name=org.testcontainers.jdbc.ContainerDatabaseDriver
【讨论】:
jdbc,对吧?我的一个容器包含一个 LDAP 服务器。同样在一个环境中 - 我没有可用的 docker-engine。因此,如果容器甚至存在且处于活动状态,则会出现异常。所以为了解决我的问题——容器不应该被注入。甚至不应该检查 docker-engine。
dev 配置文件中使用 Docker - 我的本地数据库也通过 Docker 提供,所以无论哪种方式它都会被淘汰!跨度>