Testcontainers-java: Example needed: Singleton container

Created on 12 Jan 2019  路  4Comments  路  Source: testcontainers/testcontainers-java

There is a pattern which we never documented but it is helpful when you want to have a single container per JVM. We call it "Singleton container".

The idea is trivial and does not depend on any testing framework:

First, define a base class for the tests, let's say AbstractIntegrationTest.
Then, define a container as a static property:

class AbstractIntegrationTest {
    public static final GenericContainer redis = new GenericContainer(...)
                                                             .withExposedPorts(...); 
}

Now we need to start it, but only once. Without relying on the testing framework, we can do it with a static block (JVM will trigger it only once, on class loading):

class AbstractIntegrationTest {
    public static final GenericContainer redis = ...; 

    static {
        redis.start();
    }
}

That's it! Every test class with extends AbstractIntegrationTest will have a container started & running, and the container will be terminated only on JVM shutdown.

An example should have at least 2 different classes with the tests to demonstrate it.

good first issue

Most helpful comment

@kiview : I already started with it, I will have my PR ASAP!

All 4 comments

I would like to take this issue.

Hey @chungngoops, this is great!
You already started with it, or have any questions?

@kiview : I already started with it, I will have my PR ASAP!

Does this example support running tests ,
examples/singleton-container/src/test/java/com/example/BarConcreteTestClass.java and
examples/singleton-container/src/test/java/com/example/FooConcreteTestClass.java
in parallel ?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

michael-simons picture michael-simons  路  3Comments

naderghanbari picture naderghanbari  路  3Comments

ayedo picture ayedo  路  3Comments

McKratt picture McKratt  路  4Comments

itudoben picture itudoben  路  3Comments