Embedded Postgres for Spring Boot Tests

后端 未结 5 1475
时光说笑
时光说笑 2020-12-07 17:23

I\'m building a Spring Boot app, backed by Postgres, using Flyway for database migrations. I\'ve been bumping up against issues where I cannot produce a migration that gener

5条回答
  •  半阙折子戏
    2020-12-07 17:28

    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:

    
      io.zonky.test
      embedded-database-spring-test
      1.1.0
      test
    
    

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

提交回复
热议问题