📘 Premium Read: Access my best content on
Medium member-only articles
— deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed.
Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount):
Explore My Udemy Courses
— Learn through real-time, project-based development.
In this tutorial, we will learn how to test repository or DAO layer using Spring boot provided @DataJpaTest annotation.
We will write a JUnit 5 test case for CRUD operations - Create, Read, Update and Delete.
YouTube Video
@DataJpaTest Annotation Overview
The Spring boot provides @DataJpaTest annotation. This annotation will disable full auto-configuration and instead apply only configuration relevant to JPA tests. By default, it will use an embedded, in-memory H2 database instead of the one declared in the configuration file, for faster test running time as compared to disk file database.
The @DataJpaTest annotation doesn’t load other Spring beans (@Component, @Controller, @Service, and annotated beans) into ApplicationContext.
We will create Spring Boot project from scratch using Spring data JPA ( Hibernate) and H2 database.
Let's create an entity package inside a base package "net.javaguides.springboot". Within the entity package, create a Employee class with the following content:
@Data: This annotation is from the Lombok library and is used to automatically generate getters and setters for all fields in the class, as well as implementations of toString(), equals(), and hashCode(). This reduces the amount of boilerplate code that needs to be written.
@AllArgsConstructor: This annotation is also from Lombok and generates a constructor that takes all of the fields in the class as arguments.
@NoArgsConstructor: This annotation is also from Lombok and generates a no-argument constructor.
@Builder: This annotation is also from Lombok and generates a builder pattern for the class, which provides a convenient way to create instances of the class with default or optional values for some fields.
@Entity: This annotation is from the Java Persistence API (JPA) and marks the class as an entity that can be persisted to a database.
@Table(name = "employees"): This annotation specifies the name of the table that corresponds to this entity in the database.
4. Create Spring Data JPA Repository
The next thing we’re gonna do is create a repository to access a User’s data from the database.
The JpaRepository interface defines methods for all the CRUD operations on the entity, and a default implementation of the JpaRepository called SimpleJpaRepository.
Let's create a repository package inside a base package "net.javaguides.springdatarest". Within the repository package, create a EmployeeRepository interface with the following content:
5. CRUD JUnit Tests for Spring Data JPA Repository
Spring Boot provides the @DataJpaTest annotation to test the persistence layer components that will autoconfigure in-memory embedded databases and scan for @Entity classes and Spring Data JPA repositories. The @DataJpaTest annotation doesn’t load other Spring beans (@Components, @Controller, @Service, and annotated beans) into ApplicationContext.
We need to specify the execution order because JUnit doesn’t run test methods in the order they appear in the code. So we need to use the @TestMethodOrder and @Order annotations to execute test cases in ascending order.
Head over to test package. Let's create a repository package inside a base package "test.net.javaguides.springboot". Within the repository package, create a EmployeeRepositoryTestclass with the following content:
Let's understand above JUnit test cases one by one.
JUnit test for saveEmployee:
// JUnit test for saveEmployee
@Test
@Order(1)
@Rollback(value = false)
public void saveEmployeeTest(){
Employee employee = Employee.builder()
.firstName("Ramesh")
.lastName("Fadatare")
.email("ramesh@gmail.com")
.build();
employeeRepository.save(employee);
Assertions.assertThat(employee.getId()).isGreaterThan(0);
}
Note that we have used @Rollback(false) to disable roll back to the data will be committed to the database and available for the next test methods which will run separately.
We have also used assertThat() method from AssertJ library for more readability than using JUnit’s assertion methods.
JUnit test for getEmployee:
We write a test to retrieve employee by it's Id and test the same with id 1:
Note that we have used @Rollback(false) to disable roll back to the data will be committed to the database and available for the next test methods which will run separately.
We have also used assertThat() method from AssertJ library for more readability than using JUnit’s assertion methods.
JUnit test for deleteEmployee:
We write a JUnit test method to test delete employee operation:
sir, please write test cases for controller layer for crud operations. please.
ReplyDelete