问题描述
我正在使用带有 Spring Boot 的 TestContainers 来为这样的存储库运行单元测试:
I'm using TestContainers with Spring Boot to run unit tests for repositories like this:
@Testcontainers
@ExtendWith(SpringExtension.class)
@ActiveProfiles("itest")
@SpringBootTest(classes = RouteTestingCheapRouteDetector.class)
@ContextConfiguration(initializers = AlwaysFailingRouteRepositoryShould.Initializer.class)
@TestExecutionListeners(listeners = DependencyInjectionTestExecutionListener.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Tag("docker")
@Tag("database")
class AlwaysFailingRouteRepositoryShould {
@SuppressWarnings("rawtypes")
@Container
private static final PostgreSQLContainer database =
new PostgreSQLContainer("postgres:9.6")
.withDatabaseName("database")
.withUsername("postgres")
.withPassword("postgres");
但现在我有 14 个这样的测试,每次运行测试时都会启动一个新的 Postgres 实例.是否可以在所有测试中重用同一个实例?单例模式没有帮助,因为每次测试都会启动一个新应用程序.
But now I have 14 of these tests and every time a test is run a new instance of Postgres is spun up. Is it possible to reuse the same instance across all tests? The Singleton pattern doesn't help since every test starts a new application.
我也在 .testcontainers.properties
和 .withReuse(true)
中尝试了 testcontainers.reuse.enable=true
,但是没有帮助.
I've also tried testcontainers.reuse.enable=true
in .testcontainers.properties
and .withReuse(true)
, but that didn't help.
推荐答案
如果您想拥有可重用的容器,则不能使用 JUnit Jupiter 注释 @Container
.此注释确保在每次测试后停止容器.
You can't use the JUnit Jupiter annotation @Container
if you want to have reusable containers. This annotation ensures to stop the container after each test.
您需要的是单例容器方法,并使用例如@BeforeAll
来启动你的容器.即使您在多个测试中使用了 .start()
,如果您选择同时使用 .withReuse(true)
上的可重用性,Testcontainers 也不会启动新容器您的容器定义和主目录中的以下 .testcontainers.properties
文件:
What you need is the singleton container approach, and use e.g. @BeforeAll
to start your containers. Even though you then have .start()
in multiple tests, Testcontainers won't start a new container if you opted-in for reusability using both .withReuse(true)
on your container definition AND the following .testcontainers.properties
file in your home directory:
testcontainers.reuse.enable=true
一个简单的例子可能如下所示:
A simple example might look like the following:
@SpringBootTest
public class SomeIT {
public static GenericContainer postgreSQLContainer = new PostgreSQLContainer().
withReuse(true);
@BeforeAll
public static void beforeAll() {
postgreSQLContainer.start();
}
@Test
public void test() {
}
}
和另一个集成测试:
@SpringBootTest
public class SecondIT {
public static GenericContainer postgreSQLContainer = new PostgreSQLContainer().
withReuse(true);
@BeforeAll
public static void beforeAll() {
postgreSQLContainer.start();
}
@Test
public void secondTest() {
}
}
目前有一个 PR 添加了关于此的文档
我整理了一篇博文,解释了如何详细使用带有测试容器的容器.
I've put together a blog post explaining how to reuse containers with Testcontainers in detail.
这篇关于如何在多个 SpringBootTest 之间重用 Testcontainers?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!