verify() method in Mockito example
The verify() method in Mockito is used to confirm that specific interactions with mocked objects occurred. This is particularly useful in testing when you want to ensure that a certain method was called with specific arguments during the execution of your code.
Below is an example of a Spring Boot application with a service and controller layer, where the verify() method is used in a test.
Create Spring Boot Starter Project with Spring Web Dependency and execute the below example
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.4.1</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>VerifySpringBootExample</artifactId> <version>0.0.1-SNAPSHOT</version> <name>VerifySpringBootExample</name> <description>Demo project for Spring Boot</description> <url/> <licenses> <license/> </licenses> <developers> <developer/> </developers> <scm> <connection/> <developerConnection/> <tag/> <url/> </scm> <properties> <java.version>17</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Spring Boot Application
Employee.java
package com.example.demo.model; public class Employee { private String id; private String name; // Constructor, Getters, and Setters public Employee(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
EmployeeService.java
package com.example.demo.service; import com.example.demo.model.Employee; import org.springframework.stereotype.Service; @Service public class EmployeeService { public void saveEmployee(Employee employee) { // Business logic to save the employee (e.g., in a database) System.out.println("Employee saved: " + employee.getName()); } }
EmployeeController.java
package com.example.demo.controller; import com.example.demo.model.Employee; import com.example.demo.service.EmployeeService; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class EmployeeController { private final EmployeeService employeeService; public EmployeeController(EmployeeService employeeService) { this.employeeService = employeeService; } @PostMapping("/employees") public void saveEmployee(@RequestBody Employee employee) { employeeService.saveEmployee(employee); } }
JUnit Test with Mockito
EmployeeControllerTest.java
package com.example.demo.controller; import com.example.demo.model.Employee; import com.example.demo.service.EmployeeService; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.*; class EmployeeControllerTest { @Mock private EmployeeService employeeService; @InjectMocks private EmployeeController employeeController; public EmployeeControllerTest() { MockitoAnnotations.openMocks(this); // Initialize mocks } @Test void testSaveEmployee() { // Arrange Employee employee = new Employee("1", "John Doe"); // Act employeeController.saveEmployee(employee); // Assert // Verify that the saveEmployee method was called once with the correct argument verify(employeeService, times(1)).saveEmployee(employee); } }
Explanation
Mocking with @Mock:
The EmployeeService is mocked, meaning its behavior can be controlled without relying on the actual implementation.
Injecting Mocks with @InjectMocks:
The EmployeeController uses the mocked EmployeeService.
verify() Method:
Confirms that the saveEmployee() method of the mocked EmployeeService was called exactly once with the specified Employee object.
Ensures that the method was invoked once. Other options like never() or atLeastOnce() can be used for different verification needs.
Why is verify() Useful?
Ensures Expected Interactions: Confirms the tested logic interacts with dependent components as intended.
Prevents Overcalls: Ensures methods are not called more times than necessary, which can highlight redundant or unwanted logic.
Readable Tests: Clearly communicates the expected interactions between components.
Output for the Test
If the method saveEmployee() is called once, the test will pass. Otherwise, it will fail with an assertion error, showing that the expected interaction didn't occur.
The above is the detailed content of verify() method in Mockito example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Start Spring using IntelliJIDEAUltimate version...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...
