首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在多个SpringBootTests之间重用测试容器?

如何在多个SpringBootTests之间重用测试容器?
EN

Stack Overflow用户
提问于 2020-06-17 17:17:54
回答 3查看 8.3K关注 0票数 9

我使用TestContainers和Spring Boot为存储库运行单元测试,如下所示:

代码语言:javascript
运行
复制
@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,但都没有用。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-06-18 13:55:19

如果您想拥有可重用的容器,就不能使用JUnit Jupiter注解@Container。此注释可确保停止容器after each test

你需要的是单例容器方法,并使用@BeforeAll来启动你的容器。即使您在多个测试中使用了.start(),如果您选择在容器定义上使用.withReuse(true)和主目录中的以下.testcontainers.properties文件实现可重用性,Testcontainers也不会启动新的容器:

代码语言:javascript
运行
复制
testcontainers.reuse.enable=true

一个简单的示例可能如下所示:

代码语言:javascript
运行
复制
@SpringBootTest
public class SomeIT {

  public static GenericContainer postgreSQLContainer = new PostgreSQLContainer().
    withReuse(true);

  @BeforeAll
  public static void beforeAll() {
    postgreSQLContainer.start();
  }

  @Test
  public void test() {

  }

}

还有另一个集成测试:

代码语言:javascript
运行
复制
@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

票数 22
EN

Stack Overflow用户

发布于 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>

票数 3
EN

Stack Overflow用户

发布于 2020-06-18 00:28:36

我不确定@Testcontainers是如何工作的,但我怀疑它可能每个类都能工作。

就像Singleton pattern中描述的那样让你的单例静态,并在你的signleton持有者的每一个测试中获得它,不要在每个测试类中定义它。

票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62425598

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档