0

我正在尝试在 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")
4

1 回答 1

0

这是一个 postgres 示例,但我认为您也可以将它重用于 MySQL。你应该看看System.setProperty("spring.datasource.url", "jdbc:postgresql://${postgres.containerIpAddress}:${postgres.firstMappedPort}/service")

时髦的:

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")
}

科特林:

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()
}
于 2019-08-24T11:10:18.480 回答