Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring H2 Test DB does not reset before each test

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?

like image 447
xxSwordy Avatar asked Jun 26 '18 06:06

xxSwordy


1 Answers

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

like image 176
C. Weber Avatar answered Oct 22 '22 22:10

C. Weber