Skip to content

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

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


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:

@SpringApplicationConfiguration(classes = myapp.class)
public class WebControllersTest {

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


I have a bean

public class DatabaseService implements InitializingBean {

which has a method

    public void afterPropertiesSet() throws Exception {"Bootstrapping data...");
        User user = createRootUser();
        if(populateDemo) {
        }"...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?


Actually, I think you want this:

@DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD)

@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.