CrateDB integration testing with Testcontainers

Testcontainers is a Java library that makes it easy to run additional services in Docker containers. This tutorial shows how you can boot up a single-node CrateDB database for your integration tests against CrateDB.

Add dependency

For this tutorial we will use Gradle. First add the following line to your dependencies in your build.gradle file:

testImplementation 'org.testcontainers:postgresql'

Define CrateDB container

CrateDB isn’t supported natively by Testcontainers. This isn’t critical though as due to CrateDBs PostgreSQL compatibility we can just build on top of a PostgreSQLContainer Testcontainer.

We do have to slightly adapt the PostgreSQLContainer though before this will work:

DockerImageName crateImage = DockerImageName.parse("crate:4.7.1")
    .asCompatibleSubstituteFor("postgres");
WaitStrategy waitStrategy = new LogMessageWaitStrategy()
    .withRegEx(".*started.*\\s")
    .withStartupTimeout(Duration.of(60, SECONDS));

@Rule
public PostgreSQLContainer cratedb = (PostgreSQLContainer) new PostgreSQLContainer(crateImage)
    .withDatabaseName("doc")
    .withUsername("crate")
    .withPassword("")
    .withCommand("crate")
    .waitingFor(waitStrategy);

First we mark the crate docker image to be compatible for a PostgreSQLContainer. Next we define the WaitStragey we use so that Testcontainers can detect if CrateDB has finished booting. As last step we initialize the PostgreSQLContainer with the crateImage, correct database, username, password and docker start command.

Now we are able to use CrateDB with Testcontainers.

Simple first test

We want to test if the integratioin works and use the following test to verify this:

    @Test
    public void cratedbTest() {
        try {
            Connection conn = cratedb.createConnection("");
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery("SELECT current_database()");
            rs.next();
            assertEquals("database correct", "crate", rs.getString(1));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

The test passes and everything works :rocket:

3 Likes