如何重用TestContainer? 第4单元

问题描述

你好::)我有3个问题:

  1. 如何在Junit 4中重新使用TestContainer?
  2. 我如何验证测试期间使用的容器数量
  3. 认情况下,为每个@Test或整个班级启动一个新容器?

谢谢您的回答


PostgresTestContainer.java

@ContextConfiguration(initializers = PostgresTestContainer.Initializer.class)
public abstract class PostgresTestContainer {


    @ClassRule
    public static PostgresqlContainer postgresContainer = new PostgresqlContainer(TCConfig.POSTGREsql_VERSION.toString())
            .withDatabaseName(TCConfig.TC_dbnAME)
            .withUsername(TCConfig.TC_USERNAME)
            .withPassword(TCConfig.TC_PASSWORD);

    public static class Initializer implements ApplicationContextinitializer<ConfigurableApplicationContext> {

        private static String stringConnection = postgresContainer.getJdbcUrl();

        @Override
        public void initialize(ConfigurableApplicationContext applicationContext) {
            TestPropertyValues values = TestPropertyValues.of(
                    "spring.datasource.url=" + stringConnection,"spring.datasource.username=" + TCConfig.TC_USERNAME,"spring.datasource.password=" + TCConfig.TC_PASSWORD
            );
            values.applyTo(applicationContext);
        }
    }
}

Postgresql12Test.java


@RunWith(springrunner.class)
@SpringBoottest
@ActiveProfiles("test")
public class Postgresql12_Test extends PostgresTestContainer {


    @Autowired
    private MemberService memberService;

    @Autowired
    private Flyway flyway;

    @Before
    public void initialize() {
        flyway.migrate();
    }

    @Test
    public void shoudRunPostgresqlContainer() throws Exception {
        Connection connection = DriverManager.getConnection(postgresContainer.getJdbcUrl(),postgresContainer.getUsername(),postgresContainer.getpassword());
        ResultSet resultSet = connection.createStatement().executeQuery("SELECT 666");
        resultSet.next();
        int result = resultSet.getInt(1);
        assertthat(result).isEqualByComparingTo(666);

    }
}

版本

TestContainers - Postgresql : 1.13.0
Spring Boot : 2.0.0 ( Junit 4 )
Docker : 19.03.11
Os : 20.04.1 LTS (Focal Fossa)

解决方法

  1. 如何在Junit 4中重新使用TestContainer?

    它应该已经按照您编写测试的方式工作了。你有 带有@ClassRule注释的容器,因此只能加载一次。

  2. 我如何验证测试期间使用的容器数量?

    在测试方法中放置一个断点,然后在终端中运行docker ps

  3. 默认情况下为每个@Test还是整个类启动一个新容器?

    应该使用@ClassRule为该类创建它。你可以删除 该注释,然后将管理容器的生命周期 由Java本身(如果字段为静态且适用于每种测试方法,则一次 如果不是)

,

要为所有测试类重用 Container,只需使用 static 而不使用 @ClassRule@Rule


public class PostgresTestContainer {
    public static final PostgreSQLContainer POSTGRESQL_CONTAINER = new PostgreSQLContainer<>(DockerImageName.parse("postgres:9.6.12"))
            .withDatabaseName("db_name")
            .withUsername("db_user")
            .withPassword("db_pass");
    static {
        POSTGRE_SQL_CONTAINER.start();
    }
}