如何重用 TestContainer?(Junit 4)

huangapple go评论92阅读模式
英文:

How to reuse TestContainer ? (Junit 4)

问题

大家好 如何重用 TestContainer?(Junit 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);
    }
}

VERSIONS

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

Hello everyone 如何重用 TestContainer?(Junit 4) i have 3 questions :

  1. How Reuse TestContainer with Junit 4 ?
  2. How i can verify the amount of containers use during my test ?
  3. By default a new container started foreach @Test or for whole class ?

Thank you in advance for your answers


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&lt;ConfigurableApplicationContext&gt; {

        private static String stringConnection = postgresContainer.getJdbcUrl();

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

PostgreSQL12Test.java


@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles(&quot;test&quot;)
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(&quot;SELECT 666&quot;);
        resultSet.next();
        int result = resultSet.getInt(1);
        assertThat(result).isEqualByComparingTo(666);

    }
}

VERSIONS

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

答案1

得分: 1

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

    按照您编写测试的方式,它应该已经可以正常工作。您已经使用 @ClassRule 对容器进行了注解,因此它应该只会被加载一次。

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

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

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

    使用 @ClassRule 应该为整个类创建一个容器。您可以将该注解移除,然后容器的生命周期将由 Java 自身管理(如果字段是静态的,则只会创建一次;如果字段不是静态的,则会为每个测试方法创建一个容器)。

英文:
  1. How Reuse TestContainer with Junit 4?

    It should already work the way you wrote your test. You have the
    container annotated with @ClassRule so it should only be loaded once.

  2. How i can verify the amount of containers use during my test?

    Put a breakpoint in your test method and run docker ps in a terminal.

  3. By default a new container started foreach @Test or for whole class?

    With @ClassRule it should be created for the class. You can just remove
    that annotation and then the lifecycle of the container will be managed
    by java itself (once if the field is static and for every test method
    if it's not)

答案2

得分: 0

为了在所有测试类中重用容器,只需使用 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();
    }
}
英文:

To reuse Container for all test class just use static without @ClassRule or @Rule.


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

huangapple
  • 本文由 发表于 2020年9月30日 18:50:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/64136014.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定