Repository Unit Testing Flashcards
https://medium.com/javarevisited/getting-started-with-unit-testing-in-spring-boot-bada732a5baa
Configuring Database
Use an in-memory database like H2 for testing. Spring Boot will auto-configure it for you. In-memory databases like H2 are lightweight and optimized for fast operations
@DataJpaTest
Annotate your test class with @DataJpaTest. This annotation configures the minimal configuration required to test JPA applications.
@DataJpaTest will automatically configure an in-memory database, scan for @Entity classes, and configure Spring Data JPA repositories.
Example
package com.dharshi.unitTesting.repositoryTests;
@DataJpaTest
public class UserRepositoryTests {
@Autowired private UserRepository userRepository; @Test @Transactional @Rollback public void testSaveUser() { // Define test data String name = "test1"; String email = "test1@example.com"; // Create a User object with the test data User user = User.builder() .name(name) .email(email) .build(); // Save the user to the database User savedUser = userRepository.save(user); // Assert that the retrieved user is not null assertNotNull(savedUser); // Assert that the retrieved user id is not null assertNotNull(savedUser.getId()); // Assert that the retrieved user's name matches the expected name assertEquals(name, savedUser.getName()); // Assert that the retrieved user's email matches the expected email assertEquals(email, savedUser.getEmail()); }
Explanation
@DataJpaTest is used to set up a JPA test environment with an in-memory database
@Autowired injects the UserRepository into the test class.
@Transactionalensures that the test method runs within a transactional context. Changes made during the test are not persisted beyond the scope of the test method unless explicitly committed.
@Rollback Ensures that the transaction is rolled back after the test method completes, maintaining the integrity and consistency of the test database.
Summary of Repository Unit Testing
@DataJpaTest followed by
H2 DB + JUnit