Last active
April 17, 2020 20:58
-
-
Save JosephGaiser/eae558ed97f949c867093ae2891a61a8 to your computer and use it in GitHub Desktop.
Example of a testcontainer repository wrapped in a class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.foo.bar | |
import io.r2dbc.spi.ConnectionFactories | |
import org.flywaydb.core.Flyway | |
import org.springframework.data.r2dbc.core.DatabaseClient | |
import org.testcontainers.junit.jupiter.Container | |
import org.testcontainers.junit.jupiter.Testcontainers | |
private const val username = "my_username" | |
private const val password = "my_password" | |
private const val databaseName = "my_database" | |
private const val schema = "my_schema" | |
private const val postgresImage = "postgres:9.6.10-alpine" | |
private const val migrationLocations = "filesystem:db/local-migration" | |
@Testcontainers | |
class FooBarRepository { | |
@Container | |
private val database = KotlinPostgreSQLContainer(postgresImage) | |
.withUsername(username) | |
.withPassword(password) | |
.withDatabaseName(databaseName)!! | |
fun migrate() { | |
Flyway.configure() | |
.dataSource(database.jdbcUrl, username, password) | |
.locations(migrationLocations) | |
.schemas(schema) | |
.load() | |
.migrate() | |
} | |
fun getDataBaseClient() = DatabaseClient.create(ConnectionFactories.get(getConnectionString())) | |
private fun getConnectionString(): String { | |
database.start() | |
return "r2dbc:postgresql://$username:$password@localhost:${database.firstMappedPort}/$schema" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment