我使用TestContainers和Spring Boot为存储库运行单元测试,如下所示:
@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的一个新实例就会被启动。是否有可能在所有测试中重用相同的实例?Singleton pattern没有帮助,因为每次测试都会启动一个新的应用程序。
我还尝试过在.testcontainers.properties
和.withReuse(true)
中使用testcontainers.reuse.enable=true
,但都没有用。
发布于 2020-06-18 13:55:19
如果您想拥有可重用的容器,就不能使用JUnit Jupiter注解@Container
。此注释可确保停止容器after each test。
你需要的是单例容器方法,并使用@BeforeAll
来启动你的容器。即使您在多个测试中使用了.start()
,如果您选择在容器定义上使用.withReuse(true)
和主目录中的以下.testcontainers.properties
文件实现可重用性,Testcontainers也不会启动新的容器:
testcontainers.reuse.enable=true
一个简单的示例可能如下所示:
@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 that adds documentation
我整理了一篇博客文章,详细解释了how to reuse containers with Testcontainers。
发布于 2021-08-03 12:58:36
如果您决定继续使用singleton pattern,请注意"Database containers launched via JDBC URL scheme“中的警告。我花了几个小时才注意到,尽管我使用的是singleton pattern,但总是会创建一个映射到不同端口的附加容器。
总之,如果需要使用singleton pattern,请不要使用测试容器JDBC (无主机)URI,比如jdbc:tc:postgresql:<image-tag>:///<databasename>
。
发布于 2020-06-18 00:28:36
我不确定@Testcontainers
是如何工作的,但我怀疑它可能每个类都能工作。
就像Singleton pattern中描述的那样让你的单例静态,并在你的signleton持有者的每一个测试中获得它,不要在每个测试类中定义它。
https://stackoverflow.com/questions/62425598
复制相似问题