首页 > 解决方案 > 测试容器中的 GenericContainer 应该如何参数化?

问题描述

我的 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);

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

标签: testcontainers

解决方案


Testcontainers 使用自键入机制:

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

这是一个让流利的方法工作的决定,即使类正在扩展:

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

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

现在,即使有子类,它也会返回最终类型,而不仅仅是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


推荐阅读