Take a look at this: https://github.com/zonkyio/embedded-database-spring-test. Just to be clear, it's meant for integration testing. Meaning the Spring context is initialised during the individual test.
As per the tools documentation, all you need to do is to place @AutoConfigureEmbeddedDatabase
annotation above class:
@RunWith(SpringRunner.class)
@AutoConfigureEmbeddedDatabase
@ContextConfiguration("/path/to/app-config.xml")
public class FlywayMigrationIntegrationTest {
@Test
@FlywayTest(locationsForMigrate = "test/db/migration")
public void testMethod() {
// method body...
}
}
and add Maven dependency:
<dependency>
<groupId>io.zonky.test</groupId>
<artifactId>embedded-database-spring-test</artifactId>
<version>1.1.0</version>
<scope>test</scope>
</dependency>
To use it together with @DataJpaTest
you need to disable the default test database by using the annotation @AutoConfigureTestDatabase(replace = NONE)
:
@RunWith(SpringRunner.class)
@AutoConfigureTestDatabase(replace = NONE)
@AutoConfigureEmbeddedDatabase
@DataJpaTest
public class SpringDataJpaTest {
// class body...
}
To make the use more comfortable you could also create a composite annotation, something like:
@Documented
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@AutoConfigureTestDatabase(replace = NONE)
@AutoConfigureEmbeddedDatabase
@DataJpaTest
public @interface PostgresDataJpaTest {
}
..and then use it above your test class:
@RunWith(SpringRunner.class)
@PostgresDataJpaTest // custom composite annotation
public class SpringDataJpaTest {
// class body...
}