0
0
JUnittesting~10 mins

@DataJpaTest for repository testing in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks if the repository correctly saves and retrieves an entity using Spring Boot's @DataJpaTest annotation. It verifies that the saved entity can be found by its ID.

Test Code - JUnit 5 with Spring Boot @DataJpaTest
JUnit
import static org.assertj.core.api.Assertions.assertThat;

import java.util.Optional;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

@DataJpaTest
public class UserRepositoryTest {

    @Autowired
    private UserRepository userRepository;

    @Test
    void testSaveAndFindById() {
        User user = new User();
        user.setName("Alice");

        User savedUser = userRepository.save(user);

        Optional<User> foundUser = userRepository.findById(savedUser.getId());

        assertThat(foundUser).isPresent();
        assertThat(foundUser.get().getName()).isEqualTo("Alice");
    }
}

// Assume User is a simple entity with id and name fields
// UserRepository extends JpaRepository<User, Long>
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test starts and Spring Boot initializes an in-memory database and repository beanIn-memory database is ready, UserRepository bean is injected-PASS
2Creates a new User entity with name 'Alice'User object created in memory with name 'Alice' and no id yet-PASS
3Saves the User entity to the repositoryUser saved in the in-memory database with generated id-PASS
4Finds the User entity by the generated idUser entity retrieved from the databaseCheck that foundUser is presentPASS
5Asserts that the found User's name is 'Alice'User entity's name is 'Alice'foundUser.get().getName() equals 'Alice'PASS
Failure Scenario
Failing Condition: User entity is not saved or cannot be found by id
Execution Trace Quiz - 3 Questions
Test your understanding
What does @DataJpaTest do in this test?
AIt mocks the UserRepository bean
BIt runs the full Spring Boot application
CIt sets up an in-memory database and configures JPA repositories for testing
DIt disables database access
Key Result
Use @DataJpaTest to quickly test JPA repositories with an isolated in-memory database, ensuring repository methods work as expected without starting the full application.