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?