Spring JUnit 5 ExtendWith 测试容器

Spring JUnit 5 ExtendWith TestContainer

我正在尝试重新利用容器并尝试使用 JUnit5 ExtendWith 功能,但我仍然得到:

Connection to localhost:5432 refused.

如果我在每个测试中都有相同的逻辑,一切都会按预期进行。

@Testcontainers
@SpringBootTest
@ExtendWith({PostgresTestContainersExtension.class})
public class ApplicationJUnit5Test {
  @Autowired
  private HeroClassicJDBCRepository repositoryUnderTest;

  @Test
  public void test1() {
    System.out.println("junit version: " + Version.id());
    Collection<Hero> heroes = repositoryUnderTest.allHeros();
    assertThat(heroes).hasSize(1);
    repositoryUnderTest.addHero(new Hero("bb", "bb"));
    Collection<Hero> heroesAfter = repositoryUnderTest.allHeros();
    assertThat(heroesAfter).hasSize(2);
  }
}

扩展名:

 public class PostgresTestContainersExtension implements BeforeAllCallback,
BeforeTestExecutionCallback {

private static final String IMAGE_NAME = "registry.mycomp.com/db/mariadb:10.4.11";
@DynamicPropertySource
static void properties(DynamicPropertyRegistry registry) {
    registry.add("spring.datasource.url", container::getJdbcUrl);
    registry.add("spring.datasource.password", container::getPassword);
    registry.add("spring.datasource.username", container::getUsername);
}
@Container
public static PostgreSQLContainer container = new PostgreSQLContainer()
    .withUsername("duke")
    .withPassword("password")
    .withDatabaseName("test");

@Override
public void beforeAll(ExtensionContext extensionContext) {
    startContainerIfNeed();
}

@Override
public void beforeTestExecution(ExtensionContext extensionContext) {
    startContainerIfNeed();
}

public void startContainerIfNeed() {
    if (!container.isRunning()) {
        container.start();
    }
}
}

据我所知@DynamicPropertySource只能用于测试class本身或一个superclass。您必须将属性方法移过去。