带有 Kotlin 单元测试的 TestContainers PostgreSQLContainer:“没有足够的信息来推断类型变量 SELF”

veb*_*ben 10 java kotlin spring-boot testcontainers

我试图使用PostgreSQLContainerTestContainershttps://github.com/testcontainers/testcontainers-java + https://www.testcontainers.org/按顺序)进行单元测试我的JPA库。

我这样声明我的容器:

private val postgresqlContainer = PostgreSQLContainer("postgres:12-alpine")
Run Code Online (Sandbox Code Playgroud)

但是,我在Intellij IDE 中遇到以下错误:

没有足够的信息来推断类型变量 SELF

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

错误:(26, 43) Kotlin:类型推断失败:没有足够的信息来推断构造函数中的参数 SELF PostgreSQLContainer<SELF : PostgreSQLContainer<SELF!>!>(p0: String!) 请明确指定。

Kim*_*ble 20

这个技巧也有效

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


veb*_*ben 11

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

class MyPostgreSQLContainer(imageName: String) : PostgreSQLContainer<MyPostgreSQLContainer>(imageName)
Run Code Online (Sandbox Code Playgroud)

我可以这样使用它:

private val postgresqlContainer = MyPostgreSQLContainer("postgres:12-alpine")
Run Code Online (Sandbox Code Playgroud)


Séb*_*uze 6

此问题现已在 Kotlin 端修复,请参阅此博客文章了解更多详细信息。Kotlin 1.5.30 需要一个标志,并且从 Kotlin 1.6.0 开始将成为默认标志。