Spring H2 Test DB不会在每次测试之前重置 [英] Spring H2 Test DB does not reset before each test

查看:194
本文介绍了Spring H2 Test DB不会在每次测试之前重置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:正如C. Weber在评论中建议的那样,解决方案是将@Transactional添加到测试类中.

As C. Weber suggested in the comments, the solution is to add @Transactional to the test class.

我有一些使用H2内存数据库的测试.我需要在每次测试之前重置数据库.尽管我的SQL脚本在每次执行测试时都运行,但数据库未正确重置,导致删除测试后缺少所需的条目.

I have some tests that use an H2 in-memory DB. I need to reset the DB before each test. Although my SQL scripts are run each a test is executed, the DB is not properly reset, resulting in a missing needed entry after a delete test.

测试类:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureTestDatabase(replace=Replace.ANY, connection=EmbeddedDatabaseConnection.H2)
public class RepositoryTests {

    @Autowired
    private Repository repository;

    @Autowired
    private DataSource dataSource;

    @Before
    public void populateDb() {
        Resource initSchema = new ClassPathResource("database/schema.sql");
        Resource initData = new ClassPathResource("database/data.sql");
        DatabasePopulator dbPopulator = new ResourceDatabasePopulator(initSchema, initData);
        DatabasePopulatorUtils.execute(dbPopulator, dataSource);
    }

    @Test
    public void testMethod1() {
        // ...
        repository.delete("testdata");
    }

    @Test
    public void testMethod2() {
        // ...
        Object test = repository.get("testdata");
        // is null but should be an instance
    }
}

schema.sql在重新创建所有表之前将其删除. data.sql将所有需要的测试数据插入数据库.

schema.sql drops all tables before recreating them. data.sql inserts all needed test data into the DB.

单独运行testMethod2成功.但是,运行所有测试会使测试失败,并显示NullPointerException.

Running the testMethod2 alone succeeds. However, running all tests makes the test fail with a NullPointerException.

我已经成功尝试使用@DirtiesContext,但是这不是一个选择,因为每次0.1秒的测试我都无法承受20秒的启动时间.

I have successfully tried to use @DirtiesContext, however this is not an option because I can't afford to have a 20 second startup for each 0.1 second test.

还有其他解决方法吗?

推荐答案

Spring Test Framework提供了一种机制,用于实现您想要的测试行为.只需使用@Transactional注释您的Test类即可获得每个测试方法的默认回滚行为.

The Spring Test Framework provides a mechanism for the behaviour you want for your tests. Simply annotate your Test class with @Transactional to get the default rollback behaviour for each test method.

有多种方法可以配置测试的事务行为,以及一些陷阱(例如在测试方法内部使用RestTemplate),您可以在Spring手册的相应章节中了解更多信息.

There are ways to configure the transactional behaviour of tests and also some pitfalls (like using RestTemplate inside test method), which you can read more about in the corresponding chapter of the Spring manual.

Spring测试框架

这篇关于Spring H2 Test DB不会在每次测试之前重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆