使用 JUnit 测试 Spring 应用程序 - 在测试类之后保留数据

Testing Spring Application with JUnit - Keep data after testclass

我正在开发一个更大的 Spring 启动应用程序,它有很多测试(更像是集成测试)。我现在的工作是加快测试过程。我发现,那个testData,我们需要测试的应用程序在一次测试运行中设置多次,如果我运行多次测试classes。我们使用类似这样的方法在 classes 中设置数据(编辑:存储库和 testDataBuilder@Autowired):

@BeforeEach
public void setup() {
    if (Repository.findByShortId("someId") == null) {
        testDataBuilder.createTestData();
    }
}

在测试中class,这工作正常。但是如果我的测试运行进入下一个class,它似乎会丢弃数据(数据通常存储在数据库中,我认为在测试中数据存储在内存数据库中, 不确定。

我尝试了多种方法来完成这项工作,但最终没有任何效果:

这没有用,因为当时 spring 不 运行,@ClassRule 是 运行。

设置 testData 的最佳方法是什么,以便不是每个 testClass 都必须设置它们?

为什么您的测试 @Configuration 不通过将内存数据库中的 H2 作为依赖项来映射正确的数据库 bean?

Spring/Springboot 自动缓存上下文,您无需执行任何特殊操作。

如果您的@Repository 使用 H2 内存,那么它将在所有测试用例中缓存。

H2 可以也可以配置为写入文件(而不是内存),如果你想要它而不是内存。

By default, closing the last connection to a database closes the database. For an in-memory database, this means the content is lost.

To keep the database open, add ;DB_CLOSE_DELAY=-1 to the database URL. To keep the content of an in-memory database as long as the virtual machine is alive, use jdbc:h2:mem:test;DB_CLOSE_DELAY=-1.

jdbc:h2:~/测试;DB_CLOSE_DELAY=-1; <-- 写入文件,只要 VM 处于活动状态就禁用关闭

http://www.h2database.com/html/features.html#database_only_if_exists