带有 Kotlin 单元测试的 TestContainers PostgreSQLContainer:"Not enough information to infer type variable SELF"

TestContainers PostgreSQLContainer with Kotlin unit test: "Not enough information to infer type variable SELF"

我正在尝试使用 TestContainers (https://github.com/testcontainers/testcontainers-java + https://www.testcontainers.org/) 中的 PostgreSQLContainer 来对我的 JPA 存储库进行单元测试。

我这样声明我的容器:

private val postgresqlContainer = PostgreSQLContainer("postgres:12-alpine")

但是,我遇到以下错误,来自 Intellij IDE:

Not enough information to infer type variable SELF

我尝试启动服务时的完整错误是:

Error:(26, 43) Kotlin: Type inference failed: Not enough information to infer parameter SELF in constructor PostgreSQLContainer<SELF : PostgreSQLContainer<SELF!>!>(p0: String!) Please specify it explicitly.

TestContainers 依赖于泛型类型的构造 C<Self extends C<SELF>>,但 Kotlin 不喜欢这样。 我的解决方法是定义我自己的工厂 class:

class MyPostgreSQLContainer(imageName: String) : PostgreSQLContainer<MyPostgreSQLContainer>(imageName)

我可以这样使用它:

private val postgresqlContainer = MyPostgreSQLContainer("postgres:12-alpine")

这个技巧也有效

private val postgresqlContainer = PostgreSQLContainer<Nothing>().apply {
    withDatabaseName("x")
    withUsername("y")
    withPassword("z")
}

此问题现已在 Kotlin 端修复,请参阅 this blog post 了解更多详细信息。需要 Kotlin 1.5.30 的标志,并将成为 Kotlin 1.6.0 的默认标志。