Introduction
AssertJ is a fluent assertion library for Java that provides a rich set of assertions, better error messages, and a fluent API for writing assertions. It is designed to be easy to use and understand, making your tests more readable and maintainable. This tutorial will demonstrate how to integrate AssertJ into a Spring Boot application and cover a wide range of assertions.
To learn more about AssertJ library, check out this guide: AssertJ.
Prerequisites
- Java Development Kit (JDK) 17 or later
- Apache Maven installed
- An IDE like IntelliJ IDEA or Eclipse
Step 1: Create a Spring Boot Project
You can create a Spring Boot project using Spring Initializr or your IDE.
Using Spring Initializr
- Go to Spring Initializr.
- Select the following options:
- Project: Maven Project
- Language: Java
- Spring Boot: 3.0.0 or later
- Group:
com.example
- Artifact:
assertj-demo
- Name:
assertj-demo
- Package name:
com.example.assertj.demo
- Packaging: Jar
- Java: 17 or later
- Add the following dependencies:
- Spring Web
- Spring Data JPA
- H2 Database
- Spring Boot Starter Test
- Click "Generate" to download the project zip file.
- Extract the zip file and open the project in your IDE.
Step 2: Add AssertJ Dependency
Add the following dependencies to your pom.xml
file:
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- H2 Database -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Spring Boot Starter Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- AssertJ -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.21.0</version>
<scope>test</scope>
</dependency>
</dependencies>
Step 3: Configure Application Properties
Add the following properties to src/main/resources/application.properties
:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
Step 4: Create Entity and Repository Classes
Create the Employee Entity
Create a new Java class named Employee
in the com.example.assertj.demo
package:
package com.example.assertj.demo;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Constructors
public Employee() {}
public Employee(String name, String email) {
this.name = name;
this.email = email;
}
// Getters and Setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Create the Employee Repository
Create a new Java interface named EmployeeRepository
in the com.example.assertj.demo
package:
package com.example.assertj.demo;
import org.springframework.data.jpa.repository.JpaRepository;
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
Step 5: Create the Service Class
EmployeeService
Create a new Java class named EmployeeService
in the com.example.assertj.demo
package:
package com.example.assertj.demo;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class EmployeeService {
private final EmployeeRepository employeeRepository;
public EmployeeService(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
public List<Employee> findAll() {
return employeeRepository.findAll();
}
public Optional<Employee> findById(Long id) {
return employeeRepository.findById(id);
}
public Employee save(Employee employee) {
return employeeRepository.save(employee);
}
public void deleteById(Long id) {
employeeRepository.deleteById(id);
}
}
Step 6: Create the Controller Class
EmployeeController
Create a new Java class named EmployeeController
in the com.example.assertj.demo
package:
package com.example.assertj.demo;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/employees")
public class EmployeeController {
private final EmployeeService employeeService;
public EmployeeController(EmployeeService employeeService) {
this.employeeService = employeeService;
}
@GetMapping
public List<Employee> getAllEmployees() {
return employeeService.findAll();
}
@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable Long id) {
return employeeService.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
public Employee createEmployee(@RequestBody Employee employee) {
return employeeService.save(employee);
}
@PutMapping("/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable Long id, @RequestBody Employee employee) {
return employeeService.findById(id)
.map(existingEmployee -> {
employee.setId(existingEmployee.getId());
return ResponseEntity.ok(employeeService.save(employee));
})
.orElse(ResponseEntity.notFound().build());
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteEmployee(@PathVariable Long id) {
return employeeService.findById(id)
.map(employee -> {
employeeService.deleteById(id);
return ResponseEntity.noContent().build();
})
.orElse(ResponseEntity.notFound().build());
}
}
Step 7: Create the Main Application Class
Create a main application class named AssertjDemoApplication
in the com.example.assertj.demo
package:
package com.example.assertj.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AssertjDemoApplication {
public static void main(String[] args) {
SpringApplication.run(AssertjDemoApplication.class, args);
}
}
Explanation: The AssertjDemoApplication
class contains the main
method, which is the entry point of the Spring Boot application. The @SpringBootApplication
annotation is a convenience annotation that adds all the following:
@Configuration
: Tags the class as a source of bean definitions for the application context.@EnableAutoConfiguration
: Tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.@ComponentScan
: Tells Spring to look for other components, configurations, and services in the specified package.
Step 8: Create AssertJ Test Classes
Test the EmployeeService with AssertJ
Create a new test class named EmployeeServiceTest
in the src/test/java/com/example/assertj/demo
package:
package com.example.assertj.demo;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import java.util.Optional;
@SpringBootTest
public class EmployeeServiceTest {
@Autowired
private EmployeeService employeeService;
@Test
public void testFindAll() {
List<Employee> employees = employeeService.findAll();
Assertions.assertThat(employees).isNotNull().isEmpty();
}
@Test
public void testSave() {
Employee employee = new Employee("Amit Sharma", "amit.sharma@example.com");
Employee savedEmployee = employeeService.save(employee);
Assertions.assertThat(savedEmployee.getId()).isNotNull();
Assertions.assertThat(savedEmployee.getName()).isEqualTo("Amit Sharma");
}
@Test
public void testFindById() {
Employee employee = new Employee("Rohit Sharma", "rohit.sharma@example.com");
Employee savedEmployee
= employeeService.save(employee);
Optional<Employee> foundEmployee = employeeService.findById(savedEmployee.getId());
Assertions.assertThat(foundEmployee).isPresent();
Assertions.assertThat(foundEmployee.get().getName()).isEqualTo("Rohit Sharma");
}
@Test
public void testDeleteById() {
Employee employee = new Employee("Suresh Kumar", "suresh.kumar@example.com");
Employee savedEmployee = employeeService.save(employee);
employeeService.deleteById(savedEmployee.getId());
Optional<Employee> foundEmployee = employeeService.findById(savedEmployee.getId());
Assertions.assertThat(foundEmployee).isNotPresent();
}
}
Explanation
Annotations and Class-Level Setup
@SpringBootTest
: This annotation is used to load the complete application context, allowing us to test the Spring Boot application as a whole.
Dependency Injection
@Autowired private EmployeeService employeeService;
: This injects theEmployeeService
into the test class, allowing us to call its methods and test its functionality.
Test Methods and Assertions
-
testFindAll
Method@Test public void testFindAll() { List<Employee> employees = employeeService.findAll(); Assertions.assertThat(employees).isNotNull().isEmpty(); }
- This method tests the
findAll
method ofEmployeeService
. - It retrieves all employees and asserts that the list is not null and is empty.
- AssertJ Assertions:
assertThat(employees).isNotNull()
: Asserts that theemployees
list is not null.assertThat(employees).isEmpty()
: Asserts that theemployees
list is empty.
- This method tests the
-
testSave
Method@Test public void testSave() { Employee employee = new Employee("Amit Sharma", "amit.sharma@example.com"); Employee savedEmployee = employeeService.save(employee); Assertions.assertThat(savedEmployee.getId()).isNotNull(); Assertions.assertThat(savedEmployee.getName()).isEqualTo("Amit Sharma"); }
- This method tests the
save
method ofEmployeeService
. - It creates a new
Employee
object, saves it, and asserts that theid
of the saved employee is not null and thename
is equal to "Amit Sharma". - AssertJ Assertions:
assertThat(savedEmployee.getId()).isNotNull()
: Asserts that theid
of the saved employee is not null.assertThat(savedEmployee.getName()).isEqualTo("Amit Sharma")
: Asserts that thename
of the saved employee is "Amit Sharma".
- This method tests the
-
testFindById
Method@Test public void testFindById() { Employee employee = new Employee("Rohit Sharma", "rohit.sharma@example.com"); Employee savedEmployee = employeeService.save(employee); Optional<Employee> foundEmployee = employeeService.findById(savedEmployee.getId()); Assertions.assertThat(foundEmployee).isPresent(); Assertions.assertThat(foundEmployee.get().getName()).isEqualTo("Rohit Sharma"); }
- This method tests the
findById
method ofEmployeeService
. - It creates and saves a new
Employee
object, retrieves it byid
, and asserts that the employee is present and thename
is equal to "Rohit Sharma". - AssertJ Assertions:
assertThat(foundEmployee).isPresent()
: Asserts that the employee is present.assertThat(foundEmployee.get().getName()).isEqualTo("Rohit Sharma")
: Asserts that thename
of the found employee is "Rohit Sharma".
- This method tests the
-
testDeleteById
Method@Test public void testDeleteById() { Employee employee = new Employee("Suresh Kumar", "suresh.kumar@example.com"); Employee savedEmployee = employeeService.save(employee); employeeService.deleteById(savedEmployee.getId()); Optional<Employee> foundEmployee = employeeService.findById(savedEmployee.getId()); Assertions.assertThat(foundEmployee).isNotPresent(); }
- This method tests the
deleteById
method ofEmployeeService
. - It creates and saves a new
Employee
object, deletes it byid
, and asserts that the employee is not present. - AssertJ Assertions:
assertThat(foundEmployee).isNotPresent()
: Asserts that the employee is not present after deletion.
- This method tests the
Step 9: Run the Tests
You can run the tests using your IDE or by executing the following command in the terminal:
mvn test
You should see output indicating that all tests have passed successfully.
Conclusion
In this tutorial, we demonstrated how to integrate AssertJ into a Spring Boot application and covered a wide range of assertions. We created a simple Spring Boot application with Employee
entity, repository, service, and controller layers, and wrote AssertJ test cases to test the service layer.
By following these steps, you can efficiently use AssertJ to write fluent and expressive assertions, making your tests more readable and maintainable.
Comments
Post a Comment
Leave Comment