问题描述
我在scala上,并且我有多个针对不同类(测试套件)的测试文件,每个文件都使用testcontainer(从同一脚本初始化)。
当我启动项目中的所有测试时,所有测试均失败(由于testContainers,数据库连接出现问题)。
当我分别启动测试时,所有测试都会成功。
是否可以仅启动一个容器来存储多个测试文件(测试套件)? TestContainerForAll
似乎仅适用于同一文件中的测试。
在@Matthias Berndt回复后编辑:
这里是我正在使用的库:
- “ org.scalatest” %%“ scalatest”%“ 3.0.8”
- “ com.dimafeng” %%“ testcontainers-scala-scalatest”%“ 0.38.1”
- “ com.dimafeng” %%“ testcontainers-scala-postgresql”%“ 0.38.1”
这是我的代码
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()
}
解决方法
(用Java术语来说)其中一个选项是创建抽象基类,将容器声明为静态变量并在测试中扩展该类。在这种情况下,仅在加载基类时创建一次容器。
,假设您正在使用Scalatest,则应该可以使用嵌套套件。我这里以MySQL为例,因为这就是testcontainers-scala的用法:
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
}
}