verify() method in Mockito example

Pile-T5


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>

Enter fullscreen mode

Exit fullscreen mode

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;
    }
}

Enter fullscreen mode

Exit fullscreen mode

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());
    }
}

Enter fullscreen mode

Exit fullscreen mode

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);
    }
}

Enter fullscreen mode

Exit fullscreen mode

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);
    }
}

Enter fullscreen mode

Exit fullscreen mode

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.



Source link
lol

By stp2y

Leave a Reply

Your email address will not be published. Required fields are marked *

No widgets found. Go to Widget page and add the widget in Offcanvas Sidebar Widget Area.