Embedded Postgres for Spring Boot Tests

后端 未结 5 1478
时光说笑
时光说笑 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:27

    Another quite clean solution to that problem is to use the TestContainers library. The only caveat is that it requires Docker.

    Integration Test:

    @RunWith(SpringRunner.class)
    @SpringBootTest
    @ContextConfiguration(initializers = {ApplicationTestsIT.Initializer.class})
    public class ApplicationTestsIT {
    
        private static int POSTGRES_PORT = 5432;
    
        @Autowired
        private FooRepository fooRepository;
    
        @ClassRule
        public static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres")
                .withDatabaseName("foo")
                .withUsername("it_user")
                .withPassword("it_pass")
                .withInitScript("sql/init_postgres.sql");
    
        static class Initializer implements ApplicationContextInitializer {
            public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
                TestPropertyValues.of(
                        "spring.data.postgres.host=" + postgres.getContainerIpAddress(),
                        "spring.data.postgres.port=" + postgres.getMappedPort(POSTGRES_PORT),
                        "spring.data.postgres.username=" + postgres.getUsername(),
                        "spring.data.postgres.password=" + postgres.getPassword()
                ).applyTo(configurableApplicationContext.getEnvironment());
            }
        }
    
        @Test
        public void fooRepositoryTestIT() {
            ...
        }
    

    Dependency configuration:
    pom.xml:

    
        org.testcontainers
        postgresql
        test
    
    

    build.gradle:

    testCompile "org.testcontainers:postgresql:x.x.x"
    

    Links:
    TestContainers - Databases
    TestContainers - Postgres Module

提交回复
热议问题