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.
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.
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>
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Spring Boot initializes an in-memory database and repository bean | In-memory database is ready, UserRepository bean is injected | - | PASS |
| 2 | Creates a new User entity with name 'Alice' | User object created in memory with name 'Alice' and no id yet | - | PASS |
| 3 | Saves the User entity to the repository | User saved in the in-memory database with generated id | - | PASS |
| 4 | Finds the User entity by the generated id | User entity retrieved from the database | Check that foundUser is present | PASS |
| 5 | Asserts that the found User's name is 'Alice' | User entity's name is 'Alice' | foundUser.get().getName() equals 'Alice' | PASS |