Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How GenericContainer from test containers should be parametrised?

I am getting errors in my IDE about:

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.

I've checked documentation and creators use everywhere raw type also: https://www.testcontainers.org/quickstart/junit_4_quickstart/ f.e.:

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

I dont understand this approach. Can Anyone explain how should I parametrize GenericContainer<>?

like image 986
masterdany88 Avatar asked Feb 20 '26 10:02

masterdany88


1 Answers

Testcontainers uses the self-typing mechanism:

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

This was a decision to make fluent methods work even if the class is being extended:

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

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

Now, even if there is a child class, it will return the final type, not just GenericContainer:

class MyContainer extends GenericContainer< MyContainer> {
}

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

FYI it is scheduled for Testcontainers 2.0 to change the approach, you will find more info in the following presentation:
https://speakerdeck.com/bsideup/geecon-2019-testcontainers-a-year-in-review?slide=74

like image 56
bsideup Avatar answered Feb 27 '26 08:02

bsideup