我正尝试在spring中运行一个使用数据访问层的集成测试,但为此,我需要连接到一个数据库,以便运行应用程序bean进行测试。我的一些测试涉及使用数据库持久化数据,这就是为什么我选择testContainers来使用docker运行我的数据库测试。这里的问题是,我已经有了自己的sql映像,其中包含测试所需的填充条目,并且我不想为了测试从头开始创建一个空数据库,我希望使用自己的映像进行测试。但是我不知道如何从docker镜像配置我的spring boot的数据源,因为对于通用容器,我们没有getJDBCUrl()函数或任何可以帮助我进行配置的东西。我知道如果我直接使用Mysql镜像,配置数据源会很容易。但对于这一次,我想使用我的图像。
@ClassRule
val databaseContainer: KGenericContainer = KGenericContainer("myOwnSqlImage:latest")
.withEnv("MYSQL_DATABASE", "databaseNamer")
.withEnv("MYSQL_USER", "root")
.withEnv("MYSQL_ROOT_PASSWORD", "root-password")发布于 2019-08-24 19:10:18
这是一个postgres示例,但我认为您也可以在MySQL中重用它。你应该看看System.setProperty("spring.datasource.url", "jdbc:postgresql://${postgres.containerIpAddress}:${postgres.firstMappedPort}/service")
Groovy:
static {
def postgres = new GenericContainer("postgres:10").with {
addEnv("POSTGRES_DB", "service")
addEnv("POSTGRES_USERNAME", "postgres")
addEnv("POSTGRES_PASSWORD", "postgres")
withExposedPorts(5432)
}
postgres.start()
System.setProperty("spring.datasource.url", "jdbc:postgresql://${postgres.containerIpAddress}:${postgres.firstMappedPort}/service")
}Kotlin:
class Test {
companion object {
fun database() {
val postgres = KGenericContainer("postgres:10")
postgres.addEnv("POSTGRES_DB", "service")
postgres.addEnv("POSTGRES_USERNAME", "postgres")
postgres.addEnv("POSTGRES_PASSWORD", "postgres")
postgres.withExposedPorts(5432)
postgres.start()
System.setProperty("spring.datasource.url", "jdbc:postgresql://${postgres.containerIpAddress}:${postgres.firstMappedPort}/service")
}
}
init {
database()
}
class KGenericContainer(dockerImageName: String) : GenericContainer<KGenericContainer>(dockerImageName)
}
fun main() {
Test()
}https://stackoverflow.com/questions/56991196
复制相似问题