Embedded Databases for Tests
Configure and utilize in-memory or embedded databases for fast and isolated integration testing.
Embedded Databases for Tests is a free Testing Mastery: JUnit, Mockito & Integration Tests lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Testing Mastery: JUnit, Mockito & Integration Tests learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Embedded DBs for Tests
When writing integration tests for Spring Boot applications, especially those interacting with a database, you need a database instance for your tests to run against.
Embedded databases provide a lightweight, in-memory solution that's perfect for this scenario.
Why Use Embedded DBs?
Embedded databases offer several key benefits for testing:
- Isolation: Each test run gets a clean, fresh database, preventing side effects.
- Speed: Being in-memory, they are incredibly fast, reducing test execution time.
- Simplicity: No need for external database servers or complex setup.
- Repeatability: Tests are consistent because they always start with the same data state.
H2 & HSQLDB Options
Two popular choices for embedded databases in Java applications are H2 Database and HSQLDB.
- H2: A fast, open-source, JDBC-compliant in-memory database. It's widely used with Spring Boot.
- HSQLDB: Another lightweight, relational database written in Java.
We'll focus on H2 as it's a common default in Spring Boot.
Adding H2 Dependency
To use H2 in your Spring Boot project, you typically add it as a test scope dependency in your pom.xml (for Maven) or build.gradle (for Gradle).
This ensures it's only available during testing.
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>Spring Boot Auto-Config
One of Spring Boot's magic tricks is auto-configuration. When it detects H2 on the classpath during tests, it automatically configures an in-memory H2 database for you.
You often don't need to specify a database URL in application.properties for tests, making setup trivial!
User Entity & Repository
Let's consider a simple User entity and a UserRepository. We want to test if our repository correctly saves and retrieves users.
These are standard JPA components.
// User.java
package com.coddykit.demo;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
public User() {}
public User(String name, String email) {
this.name = name;
this.email = email;
}
// Getters and Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}
// UserRepository.java
package com.coddykit.demo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByName(String name);
}@DataJpaTest with H2
Spring Boot provides @DataJpaTest specifically for testing JPA components. It auto-configures an in-memory database (like H2 if present) and an EntityManager.
It also rolls back transactions after each test, ensuring a clean state.
UserRepository Test Example
Here's how you might write an integration test for our UserRepository using H2 and @DataJpaTest:
package com.coddykit.demo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import static org.assertj.core.api.Assertions.assertThat;
@DataJpaTest
class UserRepositoryTest {
@Autowired
private TestEntityManager entityManager;
@Autowired
private UserRepository userRepository;
@Test
void whenFindByName_thenReturnUser() {
// given
User alice = new User("Alice", "alice@example.com");
entityManager.persist(alice);
entityManager.flush();
// when
User found = userRepository.findByName(alice.getName());
// then
assertThat(found.getName()).isEqualTo(alice.getName());
assertThat(found.getEmail()).isEqualTo(alice.getEmail());
}
@Test
void whenInvalidName_thenReturnNull() {
// when
User found = userRepository.findByName("InvalidName");
// then
assertThat(found).isNull();
}
}Schema & Data Initialization
For more complex scenarios, you might need to pre-populate your in-memory database with a schema or initial data.
- Place
schema.sqlinsrc/test/resourcesfor DDL (Data Definition Language). - Place
data.sqlinsrc/test/resourcesfor DML (Data Manipulation Language).
Spring Boot will automatically pick these up for your tests.
Quick Check
Which of the following is NOT a primary benefit of using an embedded database like H2 for Spring Boot integration tests?
Recap & Next Steps
We've explored how embedded databases like H2 are invaluable for fast and isolated Spring Boot integration tests.
- They offer speed, isolation, and simplicity.
- Spring Boot auto-configures them with minimal effort.
@DataJpaTestsimplifies testing JPA repositories with these databases.- You can initialize schemas and data using
schema.sqlanddata.sql.
Next, you might explore testing RESTful APIs with MockMvc!
Frequently asked questions
Is the “Embedded Databases for Tests” lesson free?
Yes — the full text of “Embedded Databases for Tests” is free to read here on the web, and the Testing Mastery: JUnit, Mockito & Integration Tests course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Testing Mastery: JUnit, Mockito & Integration Tests course, upgrade to CoddyKit PRO.
What will I learn in “Embedded Databases for Tests”?
Configure and utilize in-memory or embedded databases for fast and isolated integration testing. You practise Testing Mastery: JUnit, Mockito & Integration Tests with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Testing Mastery: JUnit, Mockito & Integration Tests?
No prior experience is required. Testing Mastery: JUnit, Mockito & Integration Tests on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Embedded Databases for Tests” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Testing Mastery: JUnit, Mockito & Integration Tests lesson?
Yes. Every Testing Mastery: JUnit, Mockito & Integration Tests lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Spring Test Context Framework
- Testing RESTful APIs
- Embedded Databases for Tests
- Testing Web Layers with @WebMvcTest and MockMvc