Search code examples
spring-boot-test

How to run spring boot integration tests isolated?


I would like to run the spring boot integration tests completly isolated from each other (this was Kent Beck's idea for unit tests). So even with a new h2 db for every test case. But I didn't find something helpful about this. Only: use @Before and so on... But this isn't a good solution.

Is this even possible? How?

Of course: I don't care about resource or time efficiency.

Atm I use junit 4.13 and spring-boot-starter-test 2.2.6.


Solution

  • You need to do something like this.

    import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
    import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
    import org.springframework.test.annotation.DirtiesContext;
    import org.springframework.test.annotation.DirtiesContext.ClassMode;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.junit.runner.RunWith;
    import org.springframework.test.context.junit4.SpringRunner;
    
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    @DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD)
    @AutoConfigureTestDatabase(replace = Replace.ANY)
    public class YourTest{
    
    }
    

    The DirtiesContext annotation

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

    The AutoConfigureTestDatabase annotation

    Annotation that can be applied to a test class to configure a test database to use instead of any application defined or auto-configured DataSource.