Testing Repositories
@DataJpaTest is a test slice that starts only the database layer. It loads the repository and a test database, so the test checks real saving and reading.
Test the database layer
This mark starts only the database layer. The test class holds the test methods.
@DataJpaTest
class TaskRepositoryTest {
}Save one task
This line saves a task with the title Buy milk. The done flag is false.
repository.save(new Task("Buy milk", false));Read every task
This line checks that exactly one task comes back. The count proves the save worked.
assertEquals(1, repository.findAll().size());Example
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
import static org.junit.jupiter.api.Assertions.assertEquals;
@DataJpaTest
class TaskRepositoryTest {
@Autowired
private TaskRepository repository;
@Test
void saveAndReadOneTask() {
repository.save(new Task("Buy milk", false));
assertEquals(1, repository.findAll().size());
}
}Key points
- @DataJpaTest loads the repository and a test database.
- The test database is H2, held in memory.
- H2 is a small database that lives only while the test runs.
- Each test starts with an empty database.
- Save a task, then read it back to prove the repository works.
In this example, @DataJpaTest starts only the database layer. The repository field is filled in by Spring. The test saves one task with the title Buy milk. The findAll call reads every saved task. The assertEquals call checks that exactly one task comes back. The test run reports one test run with no failures.
Note
The test rolls back its changes, so no test data stays behind.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does @DataJpaTest load?