Search code examples
javaspringspring-bootmavenspring-boot-test

Maven: Having multiple @SpringBootTests causes H2:memory database to be set up multiple times when running mvn test


I have several @SpringBootTest annotated tests. My app uses H2 in-memory database that gets set up each time the app runs.

When i run each test case individually through my IDE, all cases work. When i run mvn test however, i get SQL constraint violation errors because apparently my app is trying to set up my database again (and the data already exists, causing the errors).

Removing all @SpringBootTest cases except for one allows me to run mvn test successfully.

My question is, how do i make it so that i can run all the tests with mvn test without it trying to set up my database again? Is there some annotation that i can add for this?

Or is there a way to make the tests wait for the data to be dropped before setting it up again?

Thanks


Solution

  • Use @DirtiesContext annotation over test class(es) and/or method(s). With this the manipulated data get reverted back once that test completes.

    https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/annotation/DirtiesContext.html