Skip to content

Instantly share code, notes, and snippets.

@Opalo
Last active June 10, 2018 08:38
Show Gist options
  • Save Opalo/792c38c689fbedd762670812cb9f7e7c to your computer and use it in GitHub Desktop.
Save Opalo/792c38c689fbedd762670812cb9f7e7c to your computer and use it in GitHub Desktop.
Postgres embedded DB configuration for spring testing
// configuration (groovy)
import de.flapdoodle.embed.process.runtime.Network
import org.postgresql.ds.PGPoolingDataSource
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.DependsOn
import org.springframework.context.annotation.Profile
import ru.yandex.qatools.embed.postgresql.PostgresExecutable
import ru.yandex.qatools.embed.postgresql.PostgresProcess
import ru.yandex.qatools.embed.postgresql.PostgresStarter
import ru.yandex.qatools.embed.postgresql.config.AbstractPostgresConfig
import ru.yandex.qatools.embed.postgresql.config.PostgresConfig
import ru.yandex.qatools.embed.postgresql.distribution.Version
import javax.sql.DataSource
@Profile('test')
@Configuration
class TestDBConfig {
final PostgresConfig config = new PostgresConfig(
Version.V9_5_0,
new AbstractPostgresConfig.Net('localhost', Network.freeServerPort),
new AbstractPostgresConfig.Storage('test'),
new AbstractPostgresConfig.Timeout(),
new AbstractPostgresConfig.Credentials('user', 'pass')
)
@Bean(destroyMethod = 'stop', name = 'postgresProcess')
PostgresProcess postgresProcess() {
PostgresStarter<PostgresExecutable, PostgresProcess> runtime = PostgresStarter.getDefaultInstance()
PostgresExecutable exec = runtime.prepare(config)
PostgresProcess process = exec.start()
process
}
@Bean(destroyMethod = 'close')
@DependsOn('postgresProcess')
DataSource dataSource() {
PGPoolingDataSource ds = new PGPoolingDataSource()
ds.user = config.credentials().username()
ds.password = config.credentials().password()
ds.portNumber = config.net().port()
ds.serverName = config.net().host()
ds.databaseName = config.storage().dbName()
ds
}
}
// required dependencies (gradle) - spring dependencies omitted - used spring-boot 1.3.7.RELEASE
compile 'org.postgresql:postgresql:9.4.1209'
testCompile 'ru.yandex.qatools.embed:postgresql-embedded:1.15'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment