测试容器中的 GenericContainer 应该如何参数化?

How GenericContainer from test containers should be parametrised?

我的 IDE 中出现错误:

Raw use of parameterized class 'GenericContainer' Inspection info: Reports any uses of parameterized classes where the type parameters are omitted. Such raw uses of parameterized types are valid in Java, but defeat the purpose of using type parameters, and may mask bugs.

我检查了文档,创作者也到处使用原始类型: https://www.testcontainers.org/quickstart/junit_4_quickstart/ f.e.:

@Rule
public GenericContainer redis = new GenericContainer<>("redis:5.0.3-alpine")
                                        .withExposedPorts(6379);

我不明白这种方法。谁能解释一下我应该如何参数化 GenericContainer<>?

Testcontainers 使用 self-typing 机制:

class GenericContainer<SELF extends GenericContainer<SELF>> implements Container<SELF> {
...
}

即使 class 正在扩展,这也是让流畅的方法起作用的决定:

class GenericContainer<SELF extends GenericContainer<SELF>> implements Container<SELF> {

    public SELF withExposedPorts(Integer... ports) {
        this.setExposedPorts(newArrayList(ports));
        return self();
    }
}

现在,即使有 child class,它也会 return 最终类型,而不仅仅是 GenericContainer:

class MyContainer extends GenericContainer< MyContainer> {
}

MyContainer container = new MyContainer()
        .withExposedPorts(12345); // <- without SELF, it would return "GenericContainer"

仅供参考,Testcontainers 2.0 计划更改方法,您将在以下演示文稿中找到更多信息:
https://speakerdeck.com/bsideup/geecon-2019-testcontainers-a-year-in-review?slide=74

如果你像这样声明它

PostgreSQLContainer<?> container = new PostgreSQLContainer<>(
        "postgres:9.6.12")
        .withDatabaseName("mydb");

警告也消失了。