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

mas*_*y88 2 testcontainers

我在 IDE 中遇到以下错误:

参数化类“GenericContainer”的原始使用检查信息:报告省略类型参数的参数化类的任何使用。参数化类型的这种原始使用在 Java 中是有效的,但违背了使用类型参数的目的,并且可能掩盖错误。

我已经检查过文档,并且创作者也到处使用原始类型: https: //www.testcontainers.org/quickstart/junit_4_quickstart/fe:

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

我不明白这种方法。任何人都可以解释我应该如何参数化 GenericContainer<>?

Ste*_*ner 9

如果你声明它像

PostgreSQLContainer<?> container = new PostgreSQLContainer<>(
        "postgres:9.6.12")
        .withDatabaseName("mydb");
Run Code Online (Sandbox Code Playgroud)

警告也会消失。


bsi*_*eup 7

测试容器使用自类型机制:

class GenericContainer<SELF extends GenericContainer<SELF>> implements Container<SELF> {
...
}
Run Code Online (Sandbox Code Playgroud)

这是一个让 fluent 方法即使在扩展类的情况下也能工作的决定:

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

    public SELF withExposedPorts(Integer... ports) {
        this.setExposedPorts(newArrayList(ports));
        return self();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,即使有子类,它也会返回最终类型,而不仅仅是GenericContainer

class MyContainer extends GenericContainer< MyContainer> {
}

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

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