Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One testcontainers for multiple tests

I'm on scala, and I have multiple test files for different classes (testsuites), each of them uses testcontainers (init from the same script).

When I launch all tests in the project, all tests failed (problem connection with database due to testContainers).

When I launch separately tests, all the tests success.

Is there a way to launch only one container for multiple test files (testsuites)? TestContainerForAll seems to work only for tests in the same file.


Edit after @Matthias Berndt reply :

Here libs that I'm using :

  • "org.scalatest" %% "scalatest" % "3.0.8"
  • "com.dimafeng" %% "testcontainers-scala-scalatest" % "0.38.1"
  • "com.dimafeng" %% "testcontainers-scala-postgresql" % "0.38.1"

And here my code


trait DAOTest extends ForAllTestContainer {
  this: Suite =>

  override val container: PostgreSQLContainer = PostgreSQLContainer()
  container.container.withInitScript("extractData.sql")

  container.start()
  ConfigFactory.invalidateCaches()
  System.setProperty("jdbc.url", container.jdbcUrl)
  ConfigFactory.invalidateCaches()

}

like image 332
FTK Avatar asked Feb 04 '26 21:02

FTK


1 Answers

Assuming you're using Scalatest, it should be possible to use nested Suites. I'll use MySQL as an example here since that's what testcontainers-scala uses:

class MysqlSpec extends FlatSpec with ForAllTestContainer {

  override val container = MySQLContainer()

  override def nestedSuites = Vector(
    new SomeDatabaseTest(container)
  )
}
class SomeDatabaseTest(container: MySQLContainer) extends FlatSpec {
  it should "do something" in {
    // do stuff with the container
  }
}
like image 84
Matthias Berndt Avatar answered Feb 07 '26 22:02

Matthias Berndt