Bird
Raised Fist0
JUnittesting~20 mins

Test containers for database testing in JUnit - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Testcontainers Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of JUnit test using Testcontainers PostgreSQL
What is the output of the following JUnit test when run with Testcontainers managing a PostgreSQL database?
JUnit
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.PostgreSQLContainer;
import static org.junit.jupiter.api.Assertions.*;

public class DbTest {
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15.3")
        .withDatabaseName("testdb")
        .withUsername("user")
        .withPassword("pass");

    static {
        postgres.start();
    }

    @Test
    void testConnection() {
        String url = postgres.getJdbcUrl();
        assertTrue(url.contains("jdbc:postgresql://"));
        assertEquals("user", postgres.getUsername());
        assertEquals("pass", postgres.getPassword());
    }
}
ATest fails because getJdbcUrl() returns null
BTest fails with container startup timeout exception
CTest fails due to username mismatch assertion error
DTest passes successfully with all assertions true
Attempts:
2 left
💡 Hint
Testcontainers starts the container before tests run and provides valid connection info.
❓ assertion
intermediate
1:30remaining
Correct assertion to verify Testcontainers MySQL container is running
Which assertion correctly verifies that a MySQL Testcontainer is running during a JUnit test?
JUnit
import org.testcontainers.containers.MySQLContainer;
MySQLContainer<?> mysql = new MySQLContainer<>("mysql:8.0");
mysql.start();
AassertTrue(mysql.isRunning());
BassertEquals(true, mysql.isCreated());
CassertFalse(mysql.isRunning());
DassertNull(mysql.getJdbcUrl());
Attempts:
2 left
💡 Hint
Check the container's running state with the right method.
🔧 Debug
advanced
2:00remaining
Identify the cause of container startup failure in JUnit test
Given the following JUnit test code using Testcontainers, what is the most likely cause of the test failing with a container startup timeout?
JUnit
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.PostgreSQLContainer;

public class DbTest {
    @Test
    void testDb() {
        PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:nonexistent-tag")
            .withDatabaseName("db")
            .withUsername("user")
            .withPassword("pass");
        postgres.start();
        assertTrue(postgres.isRunning());
    }
}
AThe database name 'db' is invalid and prevents container startup
BThe Docker image tag 'postgres:nonexistent-tag' does not exist, causing startup failure
CThe username and password are missing and cause authentication failure
DThe test method is missing @BeforeAll annotation to start the container
Attempts:
2 left
💡 Hint
Check the Docker image tag correctness.
🧠 Conceptual
advanced
1:30remaining
Why use Testcontainers for database testing in CI pipelines?
Which is the best reason to use Testcontainers for database testing in continuous integration (CI) pipelines?
AIt slows down tests by requiring full OS virtualization
BIt requires manual installation of databases on CI servers
CIt provides a lightweight, disposable database instance isolated per test run
DIt uses in-memory databases that do not support real SQL features
Attempts:
2 left
💡 Hint
Think about test isolation and environment consistency.
❓ framework
expert
2:30remaining
Correct JUnit 5 lifecycle usage with Testcontainers PostgreSQL
Which code snippet correctly manages a PostgreSQL Testcontainer lifecycle using JUnit 5 annotations to start once before all tests and stop after all tests?
A
import org.junit.jupiter.api.*;
import org.testcontainers.containers.PostgreSQLContainer;

public class DbTest {
    static PostgreSQLContainer&lt;?&gt; postgres = new PostgreSQLContainer&lt;&gt;("postgres:15.3");

    @BeforeAll
    static void startContainer() {
        postgres.start();
    }

    @AfterAll
    static void stopContainer() {
        postgres.stop();
    }

    @Test
    void test() {
        Assertions.assertTrue(postgres.isRunning());
    }
}
B
import org.junit.jupiter.api.*;
import org.testcontainers.containers.PostgreSQLContainer;

public class DbTest {
    static PostgreSQLContainer&lt;?&gt; postgres = new PostgreSQLContainer&lt;&gt;("postgres:15.3");

    @BeforeEach
    void startContainer() {
        postgres.start();
    }

    @AfterEach
    void stopContainer() {
        postgres.stop();
    }

    @Test
    void test() {
        Assertions.assertTrue(postgres.isRunning());
    }
}
C
import org.junit.jupiter.api.*;
import org.testcontainers.containers.PostgreSQLContainer;

@TestInstance(TestInstance.Lifecycle.PER_METHOD)
public class DbTest {
    PostgreSQLContainer&lt;?&gt; postgres = new PostgreSQLContainer&lt;&gt;("postgres:15.3");

    @BeforeAll
    void startContainer() {
        postgres.start();
    }

    @AfterAll
    void stopContainer() {
        postgres.stop();
    }

    @Test
    void test() {
        Assertions.assertTrue(postgres.isRunning());
    }
}
D
import org.junit.jupiter.api.*;
import org.testcontainers.containers.PostgreSQLContainer;

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class DbTest {
    PostgreSQLContainer&lt;?&gt; postgres = new PostgreSQLContainer&lt;&gt;("postgres:15.3");

    @BeforeAll
    void startContainer() {
        postgres.start();
    }

    @AfterAll
    void stopContainer() {
        postgres.stop();
    }

    @Test
    void test() {
        Assertions.assertTrue(postgres.isRunning());
    }
}
Attempts:
2 left
💡 Hint
Static methods with @BeforeAll/@AfterAll require static container fields unless using PER_CLASS lifecycle.

Practice

(1/5)
1. What is the main advantage of using Testcontainers for database testing in JUnit?
easy
A. It provides a real database environment isolated for each test run.
B. It replaces the need for any database in tests with mocks.
C. It automatically writes test cases for database queries.
D. It speeds up tests by using in-memory databases only.

Solution

  1. Step 1: Understand what Testcontainers provide

    Testcontainers run real database instances inside containers, giving a fresh environment for each test.
  2. Step 2: Compare with other options

    Mocks or in-memory databases do not provide real database behavior, and Testcontainers do not auto-generate tests.
  3. Final Answer:

    It provides a real database environment isolated for each test run. -> Option A
  4. Quick Check:

    Real isolated DB environment = A [OK]
Hint: Testcontainers run real DBs isolated per test [OK]
Common Mistakes:
  • Thinking Testcontainers use mocks instead of real DBs
  • Confusing Testcontainers with in-memory databases
  • Believing Testcontainers auto-generate tests
2. Which of the following is the correct way to start a PostgreSQL container using Testcontainers in a JUnit test?
easy
A. PostgreSQLContainer postgres = new PostgreSQLContainer("latest:postgres").launch();
B. PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:latest").run();
C. PostgreSQLContainer postgres = new PostgreSQLContainer("postgres").begin();
D. PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:latest").start();

Solution

  1. Step 1: Check the correct constructor and method

    The correct constructor uses the image name string and the generic type, and the container is started with start().
  2. Step 2: Validate method names and image format

    Methods like run(), begin(), or launch() do not exist. The image name format must be "postgres:latest".
  3. Final Answer:

    PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:latest").start(); -> Option D
  4. Quick Check:

    Use start() with correct image name [OK]
Hint: Use start() method with correct image name [OK]
Common Mistakes:
  • Using wrong method names like run(), begin(), or launch()
  • Incorrect image name format
  • Omitting generic type parameter
3. Given the following JUnit test snippet using Testcontainers, what will be the output of System.out.println(postgres.getJdbcUrl());?
PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:13-alpine").start();
System.out.println(postgres.getJdbcUrl());
postgres.stop();
medium
A. The literal string "postgres:13-alpine"
B. An error because getJdbcUrl() is not available
C. A JDBC URL string like jdbc:postgresql://localhost:randomPort/test
D. Null, because the container is stopped immediately

Solution

  1. Step 1: Understand what getJdbcUrl() returns

    After starting, getJdbcUrl() returns the connection URL to the running container database.
  2. Step 2: Check container lifecycle and output

    The container is started before printing, so the URL is valid. The container stops after printing, so output is not null or error.
  3. Final Answer:

    A JDBC URL string like jdbc:postgresql://localhost:randomPort/test -> Option C
  4. Quick Check:

    getJdbcUrl() after start() returns valid URL [OK]
Hint: Call getJdbcUrl() only after container start() [OK]
Common Mistakes:
  • Calling getJdbcUrl() before start()
  • Expecting literal image name as URL
  • Assuming output is null after stop() immediately
4. Identify the error in this JUnit test using Testcontainers for MySQL:
@Test
void testDbConnection() {
  MySQLContainer mysql = new MySQLContainer("mysql:8.0");
  mysql.start();
  String url = mysql.getJdbcUrl();
  // Use url to connect
  mysql.stop();
  mysql.stop();
}
medium
A. Calling mysql.stop() twice causes an error.
B. Missing generic type parameter in MySQLContainer declaration.
C. Container must be started with run() instead of start().
D. The image name "mysql:8.0" is invalid.

Solution

  1. Step 1: Check MySQLContainer declaration

    MySQLContainer is a generic class and should be declared with a wildcard: MySQLContainer<?>.
  2. Step 2: Verify other parts

    Calling stop() twice is safe (idempotent). start() is correct method. Image name "mysql:8.0" is valid.
  3. Final Answer:

    Missing generic type parameter in MySQLContainer declaration. -> Option B
  4. Quick Check:

    Use MySQLContainer to avoid raw type warning [OK]
Hint: Always use generic type with Testcontainers classes [OK]
Common Mistakes:
  • Calling stop() multiple times causes error
  • Using run() instead of start()
  • Incorrect image name format
5. You want to write a JUnit test that uses a PostgreSQL Testcontainer and runs a SQL script to initialize the database before tests. Which approach correctly achieves this?
hard
A. Use withInitScript("init.sql") on the PostgreSQLContainer instance before starting it.
B. Manually connect after start() and run the SQL script using JDBC in each test method.
C. Include the SQL script inside the Docker image and use a custom image name.
D. Start the container, then copy the SQL file into the container using copyFileToContainer() and run it manually.

Solution

  1. Step 1: Identify Testcontainers feature for init scripts

    Testcontainers provide withInitScript() method to run SQL scripts automatically on container startup.
  2. Step 2: Compare alternatives

    Manual JDBC execution or copying files is more complex and error-prone. Custom images are possible but not necessary for simple init scripts.
  3. Final Answer:

    Use withInitScript("init.sql") on the PostgreSQLContainer instance before starting it. -> Option A
  4. Quick Check:

    Use withInitScript() for automatic DB initialization [OK]
Hint: Use withInitScript() to auto-run SQL on container start [OK]
Common Mistakes:
  • Running SQL manually in each test instead of init script
  • Modifying Docker images unnecessarily
  • Copying files manually instead of using built-in methods
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard