0
0
JUnittesting~10 mins

In-memory database testing in JUnit - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create an in-memory H2 database connection.

JUnit
Connection conn = DriverManager.getConnection("jdbc:h2:[1]", "sa", "");
Drag options to blanks, or click blank then click option'
Azip:testdb
Bfile:testdb
Ctcp://localhost/testdb
Dmem:testdb
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'file:' instead of 'mem:' causes the database to be file-based, not in-memory.
Forgetting the 'mem:' prefix leads to connection errors.
2fill in blank
medium

Complete the code to create a JUnit 5 test method that initializes the in-memory database.

JUnit
@Test
void testDatabaseConnection() throws SQLException {
    Connection conn = DriverManager.getConnection("jdbc:h2:mem:testdb", "sa", "");
    Statement stmt = conn.createStatement();
    stmt.execute([1]);
    conn.close();
}
Drag options to blanks, or click blank then click option'
A"SELECT * FROM users"
B"DROP TABLE users"
C"CREATE TABLE users(id INT PRIMARY KEY, name VARCHAR(255))"
D"INSERT INTO users VALUES(1, 'Alice')"
Attempts:
3 left
💡 Hint
Common Mistakes
Using SELECT or DROP statements before creating the table causes errors.
Trying to insert data before creating the table leads to failures.
3fill in blank
hard

Fix the error in the assertion that checks if the user count is 1.

JUnit
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM users");
rs.next();
assertEquals([1], rs.getInt(1));
Drag options to blanks, or click blank then click option'
A0
B1
C"1"
Drs.getString(1)
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string '1' instead of integer 1 causes assertion failure.
Using 0 as expected count is incorrect if one row was inserted.
4fill in blank
hard

Fill both blanks to insert a user and verify the insertion.

JUnit
stmt.executeUpdate("INSERT INTO users (id, name) VALUES ([1], '[2]')");
ResultSet rs = stmt.executeQuery("SELECT name FROM users WHERE id = 1");
rs.next();
assertEquals("Alice", rs.getString(1));
Drag options to blanks, or click blank then click option'
A1
BAlice
C2
DBob
Attempts:
3 left
💡 Hint
Common Mistakes
Using id 2 or name 'Bob' causes the assertion to fail.
Mismatching inserted values and assertion expected values.
5fill in blank
hard

Fill all three blanks to create a test that inserts multiple users and checks their count.

JUnit
stmt.executeUpdate("INSERT INTO users (id, name) VALUES ([1], '[2]')");
stmt.executeUpdate("INSERT INTO users (id, name) VALUES ([3], 'Bob')");
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM users");
rs.next();
assertEquals([4], rs.getInt(1));
Drag options to blanks, or click blank then click option'
A1
BAlice
C2
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same id for both inserts causes primary key errors.
Expecting count 1 after inserting two users causes assertion failure.