Repository Unit Testing Flashcards

https://medium.com/javarevisited/getting-started-with-unit-testing-in-spring-boot-bada732a5baa (5 cards)

1
Q

Repository Unit Testing Pureness

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Conceptual Working

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Key Concepts

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Example

A

@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);   } }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Reference data load

A

@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’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly