下面的配置在Spring Boot 2.0中运行良好。
与
embedded-database-spring-test相比的优点是,这个解决方案不会将Flyway推入类路径中,可能会干扰Spring Boot的自动配置。
@Configuration
@Slf4j
public class EmbeddedPostgresConfiguration {
@Bean(destroyMethod = "stop")
public PostgresProcess postgresProcess() throws IOException {
log.info("Starting embedded Postgres");
String tempDir = System.getProperty("java.io.tmpdir");
String dataDir = tempDir + "/database_for_tests";
String binariesDir = System.getProperty("java.io.tmpdir") + "/postgres_binaries";
PostgresConfig postgresConfig = new PostgresConfig(
Version.V10_3,
new AbstractPostgresConfig.Net("localhost", Network.getFreeServerPort()),
new AbstractPostgresConfig.Storage("database_for_tests", dataDir),
new AbstractPostgresConfig.Timeout(60_000),
new AbstractPostgresConfig.Credentials("bob", "ninja")
);
PostgresStarter<PostgresExecutable, PostgresProcess> runtime =
PostgresStarter.getInstance(EmbeddedPostgres.cachedRuntimeConfig(Paths.get(binariesDir)));
PostgresExecutable exec = runtime.prepare(postgresConfig);
PostgresProcess process = exec.start();
return process;
}
@Bean(destroyMethod = "close")
@DependsOn("postgresProcess")
DataSource dataSource(PostgresProcess postgresProcess) {
PostgresConfig postgresConfig = postgresProcess.getConfig();
val config = new HikariConfig();
config.setUsername(postgresConfig.credentials().username());
config.setPassword(postgresConfig.credentials().password());
config.setJdbcUrl("jdbc:postgresql://localhost:" + postgresConfig.net().port() + "/" + postgresConfig.storage().dbName());
return new HikariDataSource(config);
}
}
Maven:
<dependency>
<groupId>ru.yandex.qatools.embed</groupId>
<artifactId>postgresql-embedded</artifactId>
<version>2.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
该类基于我在这里找到的代码:
https://github.com/nkoder/postgresql-embedded-example。
我进行了修改,以使用
HikariDatasource
(Spring Boot的默认数据源)来实现正确的连接池。
binariesDir
和
dataDir
用于避免在重复测试中进行昂贵的提取+initdb操作。
@DataJpaTest
这样的单元测试可以在本地计算机上运行而无需安装数据库。 - SingleShot