Testng Mapped port can only be obtained after the container is started

223 阅读1分钟

在 IDEA 中使用 testng 测试自定义的 group 时,遇到如下错误

Mapped port can only be obtained after the container is started

错误的代码如下:

public class TestBase extends AbstractTestNGSpringContextTests {

    protected MockedStatic<AuthContext> authContextMockedStatic;

    private static final PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:14.7")
            .withUsername("user")
            .withPassword("password")
            .withDatabaseName("ces-drive")
            .withInitScript("liquibase/init_postgresql.sql");

    @BeforeSuite
    public void beforeSuiteTest() {
        redisServer.start();
        postgres.start();
    }

    @DynamicPropertySource
    static void configureProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", () -> postgres.getJdbcUrl() + "&currentSchema=drive");
        registry.add("spring.datasource.username", postgres::getUsername);
        registry.add("spring.datasource.password", postgres::getPassword);
    }

    @AfterSuite
    public void afterSuiteTest() {
        postgres.close();
    }
}

错误报在 19 行,意思是容器还没启动,所以获取端口失败。

通过 debug 发现 @BeforeSuite,解决方法有两种:

  1. 在 @BeforeSuite 上加上 groups 属性(和运行的 group 相同)
  2. 在 @BeforeSuite 上加上 alwaysRun = true

总结

除了 @BeforeSuite 还有 @AfterSuite,@BeforeClass,@AfterClass,也会出现这种情况,最好是所有都加上 alwaysRun = true,下篇文章来教你如何使用 IDEA 创建testng suite 和 group。