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

4

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

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

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

目前,我正在注释容器注入代码,并像这样定期检查它们。

3个回答

2

是的,可以使用配置文件来实现。

一个可能的解决方案是(利用static关键字进行操作,并假设使用.withLocalCompose(true)):

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

当需要时,请使用测试配置文件。即使在所有测试中导入该配置,它也应该仅加载“test”测试。

这个想法是提供docker环境来进行测试套件,并使用属性配置文件。

  • 可以通过本地docker引擎(“dev”)提供,您可以自行以应用程序-dev.properties中指定的适当dev URL启动容器
  • 或通过TestContainers提供,使用application-test.properties中的测试URL

由于启动容器需要时间,因此您要以静态方式仅执行一次,这将在所有类之前加载。

希望这可以帮助到您。


2

根据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);

1

一种在测试中获取容器的方法是使用JDBC URL,如文档所述。这使您可以轻松地在基于配置文件的情况下在Testcontainers和本地主机之间进行切换:

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。 - Skip
@Skip 是的,只适用于可以通过“魔术URL”进行有线连接的容器。而且我不知道它是否仍然会尝试在dev配置文件中使用Docker - 我的本地数据库是通过Docker提供的,所以无论如何都会出现问题! - jonrsharpe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接