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

10

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

我声明我的容器如下:

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

然而,在 Intellij IDE 中,我遇到了以下错误:

没有足够的信息来推断类型变量 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.

3个回答

25

这个技巧也有效

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

11

TestContainers 依赖于泛型类型 C<Self extends C<SELF>> 的构建,但是 Kotlin 不支持这种写法。

我的解决方法是定义自己的工厂类:

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

而我可以像这样使用它:

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

6

现在,Kotlin方面已经修复了此问题,请参见此博客文章以获取更多详细信息。在Kotlin 1.5.30中需要一个标志,并将成为 Kotlin 1.6.0的默认选项。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接