0

I am trying to run an integration test in spring that is using the data access layer but for that i need to connect to a database for me to run the application beans for testing. some of my testing involves using the database persisted data, so that's why i chose testContainers to run my database test using docker. The problem here is that i already have an sql image of my Own that contains populated entries that i need for testing and i don't want to create an empty database from scratch for testing, i want to use my own image for testing. but i don't know how i can configure my datasource for my spring boot from the docker image, cause with generic containers we don't have a getJDBCUrl() function or anything that would help me configure. I know its easy to configure the datasource if i am directly using the Mysql image. but for this one, i want to use my image.

@ClassRule
val databaseContainer: KGenericContainer = KGenericContainer("myOwnSqlImage:latest")
        .withEnv("MYSQL_DATABASE", "databaseNamer")
        .withEnv("MYSQL_USER", "root")
        .withEnv("MYSQL_ROOT_PASSWORD", "root-password")
Brighton
  • 1
  • 1

1 Answers1

0

It's a postgres example, but I think you can reuse it for MySQL as well. You should take a look at 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()
}
Ihar Sadounikau
  • 741
  • 6
  • 20