Spring H2 Test DB does not reset before each test

不想你离开。 提交于 2020-08-22 06:25:38

问题


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

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.

Test class:

@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 drops all tables before recreating them. data.sql inserts all needed test data into the DB.

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

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.

Is there another solution?


回答1:


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.

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 Test Framework



来源:https://stackoverflow.com/questions/51036215/spring-h2-test-db-does-not-reset-before-each-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!