yeepo
yeepo

Reputation: 100

Examining contents of TestContainers

I am using a PostgreSQL TestContainer to test Liquibase schema migration in Spring Boot. I don't have any respositories. I am wondering if I can see/access the contents of the TestContainer, and test the schema migration.

Upvotes: 4

Views: 3802

Answers (1)

rieckpil
rieckpil

Reputation: 12021

Yes, you can access the Docker container spawned by Testcontainers like any other Docker container. Using the JUnit 5 extension or the JUnit 4 rule for Testcontainers will however shut down the container after your tests.

You can use the coontainer re-usability feature for Testcontainers (in alpha state since 1.12.3) for ensuring your containers are up- and running after your tests finish.

As Testcontainers will launch the container on an ephemeral port, simply execute docker ps and check to which local port the container port is mapped. E.g.:

b0df4733babb        postgres:9.6.12      "docker-entrypoint.s…"   19 seconds ago      Up 18 seconds       0.0.0.0:32778->5432/tcp   inspiring_dewdney

You can now connect to your db on localhost:32778 with e.g. PgAdmin or the database view of IntelliJ IDEA and check your database tables.

The credentials for the access are those you specify in your test:

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

As a workaround you could also put in a breakpoint at the end of your test, debug the test, and quickly check your database.

UPDATE: If you want to verify the validity of your schema, you can use a Hibernate feature for this:

spring.jpa.hibernate.ddl-auto=validate

This will validate that your Java entity setup matches the underlying database schema on application startup. You can also add this to your production application.properties file as your application won't start if there is a mismatch (e.g. missing table, column).

For this to work in a test, you need to either use @DataJpaTest or use @SpringBootTest to the whole application context connect to your local container.

Find more information here.

Upvotes: 10

Related Questions