有没有一种方法可以根据Spring配置文件禁用Testcontainer?

时间:2020-06-03 18:35:57

标签: java spring-boot junit5 testcontainers

我正在使用Spring Boot并在Testcontainers中运行测试。

有时候(在开发时)我不希望针对Testcontainer运行测试,而是针对已经运行的容器运行测试。

是否有一种方法可以根据Spring配置文件,环境变量等来禁用Testcontainer?

现在我正在评论容器注入代码,并定期检查它们。

3 个答案:

答案 0 :(得分:2)

是的,可以使用配置文件来完成。

一种可能的解决方案是(想法是使用static关键字,并假设使用.withLocalCompose(true)):

@Configuration
@Profile("test")
public class TestDockerConfig {
    // initialize your containers in static fields/static block
}

并在需要时使用测试配置文件。即使您在所有测试中都导入了该配置,也应该只为“测试”配置加载该配置。

这个想法是提供docker环境来测试套件和使用属性配置文件。 它可以:

  • 由启动容器的本地docker引擎(“ dev”)提供 自己使用application-dev.properties中指定的正确开发URL
  • 或通过TestContainers提供,其中包含测试URL application-test.properties

由于启动容器需要花费时间,因此您只希望以静态方式执行一次操作,并且它将在所有类之前加载。

希望有帮助。

答案 1 :(得分:1)

按照谢尔盖(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);

答案 2 :(得分:0)

在测试中获取容器的一种方法就是按照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