0

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

连接到 localhost:5432 被拒绝。

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

@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();
    }
}
}
4

1 回答 1

1

据我所知@DynamicPropertySource,只能在测试类本身或超类中使用。您必须将属性方法移过来。

于 2021-08-28T06:25:19.663 回答