Hey. Im trying to get testcontainers up and runnin...
# kotest
j
Hey. Im trying to get testcontainers up and running together with kotest (5.9) and spring boot (3.2) but im having some problems getting it to work properly with liquibase and im getting this error
The driver has not received any packets from the server
. Does anyone have any good sources on how to properly set this up? Ive created a
TestListener
extension to setup a mysql container and then i add this to the test config listener.
e
Sounds like your testcontainer is unable to connect to your db. What’s running in the container and what’s running on your local machine?
t
we use postgres and flyway, but I think what is relevant might be true also for you:
Copy code
import io.kotest.core.extensions.ProjectExtension
import io.kotest.core.project.ProjectContext
import org.testcontainers.containers.JdbcDatabaseContainer
import org.testcontainers.containers.Network
import org.testcontainers.containers.PostgreSQLContainerProvider

object PostgresExtension : ProjectExtension {
  private val delegate = lazy {
    PostgreSQLContainerProvider().newInstance("14.4")
      .withNetwork(Network.SHARED)
      .withNetworkAliases("db")
  }
  private val withNetworkAliases by delegate

  override suspend fun interceptProject(context: ProjectContext, callback: suspend (ProjectContext) -> Unit) {
    beforeProject()
    callback(context)
    afterProject()
  }

  fun beforeProject() {
    withNetworkAliases.start()
    System.setProperty("spring.datasource.url", "jdbc:postgresql://${withNetworkAliases.connectionString()}")
    System.setProperty("spring.datasource.username", withNetworkAliases.username)
    System.setProperty("spring.datasource.password", withNetworkAliases.password)
    System.setProperty("spring.flyway.schemas", withNetworkAliases.databaseName)
  }

  fun afterProject() {
    if (delegate.isInitialized()) withNetworkAliases.stop()
  }

  private fun JdbcDatabaseContainer<*>.connectionString() = "$host:$firstMappedPort/$databaseName"
}
we use project extension because those are executed before Spring even starts and we can manipulate the configuration (see all those properties set) with values taken from the container. DISCLAIMER: I don't want to claim this is the right way, it's honestly not nice to look at, but does it's job
j
Thank you Marco. I managed to get it up and running via spring
ApplicationContextInitializer<ConfigurableApplicationContext>
but then it is not managed by kotest so ill see if i can use what you described.
@Emil Kantis @thanksforallthefish This made it work, but now i need to find a good solution to only run this for certain tests. The issue im having is as mentioned that it needs to run before the project itself, but ive tried using different project configs and tags but with no success. Do you have any idea how to achieve this?