Repository Unit Testing Pureness
Repository tests are not true unit tests, because:
They rely on JPA / Hibernate.
They need a database (even if in-memory).
Instead, they’re a form of lightweight integration testing — testing the persistence layer in isolation.
Conceptual Working
Starts a very lightweight Spring context — only the data layer (no web, no services).
Sets up an in-memory database (like H2) by default
Scans for @Entity and Repository classes only.
Provides a TestEntityManager so you can persist test data manually.
Key Concepts
Isolation - Only data layer is tested (no controllers, services).
In-memory DB - Fresh database created per test class (clean state).
Transactional - Each test runs in a transaction that rolls back afterward.
No Mocks - You test real JPA behavior, not mocks.
Example
@DataJpaTest
class OrderRepositoryTest {
@Autowired
private OrderRepository orderRepository;
@Test
void findByCustomerId_returnsOrders() {
// Arrange
orderRepository.save(new Order(1L, 100L, “Shoes”));
orderRepository.save(new Order(2L, 100L, “Jacket”));
// Act List<Order> result = orderRepository.findByCustomerId(100L); // Assert assertThat(result).hasSize(2); } }
Reference data load
@DataJpaTest only creates the tables and does not populate data.
your tests may fail if your entities depend on foreign keys or default data.
Use data.sql
Spring Boot automatically runs schema.sql and data.sql scripts against your test database on startup.
src/test/resources/data.sql
You can have queries in the data.sql like this
INSERT INTO country (id, code, name) VALUES (1, ‘US’, ‘United States’);
INSERT INTO country (id, code, name) VALUES (2, ‘CA’, ‘Canada’);
INSERT INTO status_type (id, code) VALUES (1, ‘ACTIVE’);