How to re-create database before each test in Spring?

Dims picture Dims · Jan 5, 2016 · Viewed 95.6k times · Source

My Spring-Boot-Mvc-Web application has the following database configuration in application.properties file:

spring.datasource.url=jdbc:h2:tcp://localhost/~/pdk
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver

this is the only config I made. No any other configurations made by me anywhere. Nevertheless the Spring and subsystems are automatically recreate database on each web application run. Database is recreated namely on system run while it contains data after application ends.

I was not understanding this defaults and was expecting this is suitable for tests.

But when I started to run tests I found that database is recreated only once. Since tests are executed at no predefined order, this is senseless at all.

So, the question is: how to make any sense? I.e. how to make database recreate before each test as it happens at application first start?

My test class header is follows:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = myapp.class)
//@WebAppConfiguration
@WebIntegrationTest
@DirtiesContext
public class WebControllersTest {

As you see, I tried @DirtiesContext at class level and it didn't help.

UPDATE

I have a bean

@Service
public class DatabaseService implements InitializingBean {

which has a method

@Override
    @Transactional()
    public void afterPropertiesSet() throws Exception {
        log.info("Bootstrapping data...");
        User user = createRootUser();
        if(populateDemo) {
            populateDemos();
        }
        log.info("...Bootstrapping completed");
    }

Now I made it's populateDemos() method to clear all data from database. Unfortunately, it does not called before each test despite @DirtiesContext. Why?

Answer

Raphael Amoedo picture Raphael Amoedo · May 16, 2016

Actually, I think you want this:

@DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD)

http://docs.spring.io/autorepo/docs/spring-framework/4.2.6.RELEASE/javadoc-api/org/springframework/test/annotation/DirtiesContext.html

@DirtiesContext may be used as a class-level and method-level annotation within the same class. In such scenarios, the ApplicationContext will be marked as dirty after any such annotated method as well as after the entire class. If the DirtiesContext.ClassMode is set to AFTER_EACH_TEST_METHOD, the context will be marked dirty after each test method in the class.

You put it on your Test class.