Skip to content

Improve usability of SQL init scripts with reusable containers #2127

@aguibert

Description

@aguibert

Background

Recently reusable container support was added to Testcontainers, which allows significant time savings during local dev/test cycles. However, there is room for improvement in the usability of reusable containers and init scripts (specifically JdbcDatabaseContainer init scripts).

Currently the JdbcDatabaseContainer class has the following method:

    public SELF withInitScript(String initScriptPath) {
        this.initScriptPath = initScriptPath;
        return self();
    }

This allows an initialization SQL script to be run after the container is started. Typically to populate some test data in the database.

Problem

When combining this mechanism with reusable containers, the init script still runs every time the tests start, even though the same DB instance is being reused. This can cause problems if the init script was not written to account for a DB instance being reused. For example, it may try to create a table that already exists from the previous run, or it may try to insert some data that is already present in the DB from the previous run.

Proposed solution

Add an overloaded method to JdbcDatabaseContainer that allows the user to specify whether or not their init script should be run when attaching to a reused container. For example:

/**
 * Runs a SQL initialization script after this container is started
 * @param initScriptPath Path to the initialization script
 * @param runOnReuse True if the initialization script should run again on a container that has already been started and is being reused. False otherwise.
 */
public SELF withInitScript(String initScriptPath, boolean runOnReuse) {
 // ...
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions