有没有办法根据 Spring 配置文件禁用 Testcontainers?

Is there a way to disable Testcontainers depending on Spring profile?

我在 Testcontainers 中使用 Spring 引导和 运行ning 测试。

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

有没有办法根据 Spring 配置文件、环境变量等来禁用 Testcontainer?

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

在测试中获取容器的一种方法是根据 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 needs to be on your application's classpath at runtime for this to work
  • For Spring Boot (Before version 2.3.0) you need to specify the driver manually spring.datasource.driver-class-name=org.testcontainers.jdbc.ContainerDatabaseDriver

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

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

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

并在需要时使用测试配置文件。即使您在所有测试中导入该配置,它也应该只加载 "test" 个。

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

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

由于启动容器需要时间,因此您只想以静态方式执行一次,并且它将在您所有 类.

之前加载

希望对您有所帮助。

正如谢尔盖在这里推荐的那样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);