如果测试失败,如何配置测试容器以离开数据库容器运行?
How to configure testcontainers to leave database container running if a test fails?
当使用 Test Containers 时,正常行为是当测试因通过或失败而结束时关闭容器。
有没有办法配置测试容器,以便在测试失败时保留数据库容器以帮助调试?
是的,您可以使用 Testcontainers 的重用功能(处于 alpha 状态)在测试后不关闭容器。
为此,您需要 Testcontainers >= 1.12.3 并选择加入属性文件 ~/.testcontainers.properties
testcontainers.reuse.enable=true
接下来,声明要重复使用的容器:
static PostgreSQLContainer postgreSQLContainer = (PostgreSQLContainer) new PostgreSQLContainer()
.withDatabaseName("test")
.withUsername("duke")
.withPassword("s3cret")
.withReuse(true);
并确保不使用 JUnit 4 或 JUnit 5 注释来管理容器的生命周期。而是使用单例容器或自己在 @BeforeEach
中启动它们:
static final PostgreSQLContainer postgreSQLContainer;
static {
postgreSQLContainer = (PostgreSQLContainer) new PostgreSQLContainer()
.withDatabaseName("test")
.withUsername("duke")
.withPassword("s3cret")
.withReuse(true);
postgreSQLContainer.start();
}
此功能的目的是加快后续测试,因为容器仍处于运行状态,运行但我想这也适合您的用例。
您可以找到详细的指南here。
当使用 Test Containers 时,正常行为是当测试因通过或失败而结束时关闭容器。
有没有办法配置测试容器,以便在测试失败时保留数据库容器以帮助调试?
是的,您可以使用 Testcontainers 的重用功能(处于 alpha 状态)在测试后不关闭容器。
为此,您需要 Testcontainers >= 1.12.3 并选择加入属性文件 ~/.testcontainers.properties
testcontainers.reuse.enable=true
接下来,声明要重复使用的容器:
static PostgreSQLContainer postgreSQLContainer = (PostgreSQLContainer) new PostgreSQLContainer()
.withDatabaseName("test")
.withUsername("duke")
.withPassword("s3cret")
.withReuse(true);
并确保不使用 JUnit 4 或 JUnit 5 注释来管理容器的生命周期。而是使用单例容器或自己在 @BeforeEach
中启动它们:
static final PostgreSQLContainer postgreSQLContainer;
static {
postgreSQLContainer = (PostgreSQLContainer) new PostgreSQLContainer()
.withDatabaseName("test")
.withUsername("duke")
.withPassword("s3cret")
.withReuse(true);
postgreSQLContainer.start();
}
此功能的目的是加快后续测试,因为容器仍处于运行状态,运行但我想这也适合您的用例。
您可以找到详细的指南here。