1

I have 6 JUnit classes into different test packages. I want to use application.properties file which is used by Spring framework to setup database connection.

The problem is how to create database connection when first JUnit test is run and reuse it for all Classes. At the end to close the connection properly.

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808

1 Answers1

1

You can use Testcontainers for this. If you want to reuse an existing database container (e.g. PostgreSQL or MySQL), make sure to use a manual container lifecycle approach and start the container once (e.g. inside an abstract test class). Testcontainers calls this Singleton containers:

abstract class AbstractContainerBaseTest {

    static final MySQLContainer MY_SQL_CONTAINER;

    static {
        MY_SQL_CONTAINER = new MySQLContainer();
        MY_SQL_CONTAINER.start();
    }
}

class FirstTest extends AbstractContainerBaseTest {

    @Test
    void someTestMethod() {
        String url = MY_SQL_CONTAINER.getJdbcUrl();

        // create a connection and run test as normal
    }
}

Once your JVM terminates, your container will be deleted.

Another approach would be the reuse feature of Testcontainers:

static PostgreSQLContainer postgreSQLContainer = (PostgreSQLContainer) new PostgreSQLContainer()
  .withDatabaseName("test")
  .withUsername("duke")
  .withPassword("s3cret")
  .withReuse(true);

If your database setup is similar for all your tests and you opt-in for this feature, Testcontainers will reuse an already started container. Keep in mind that with this approach you have to clean up the container for yourself as they stay alive after all tests finished.

rieckpil
  • 10,470
  • 3
  • 32
  • 56