doReturn() method in Mockito example

Spring Boot Example Using doReturn() in Mockito The doReturn() method in Mockito is used when you want to mock a method that is already called in a final, private, or spy object, avoiding unwanted method execution. 1. When to Use doReturn() Instead of when()? Use when().thenReturn() when mocking normal method calls. Use doReturn().when() when: Dealing with spies (partial mock objects). Avoiding unwanted method execution during testing. Mocking final/private methods indirectly. Spring Boot Application Code pom.xml 4.0.0 org.springframework.boot spring-boot-starter-parent 3.4.2 com.example DoReturnSBProject 0.0.1-SNAPSHOT DoReturnSBProject Demo project for Spring Boot 17 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin Employee.java package com.example.demo.model; public class Employee { private String id; private String name; 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 Employee getEmployeeById(String id) { System.out.println("Actual method execution!"); // Should be avoided in tests return new Employee(id, "Real Employee"); } } Unit Test Using doReturn() package com.example.demo.service; import com.example.demo.model.Employee; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.*; import static org.junit.jupiter.api.Assertions.*; class EmployeeServiceTest { @Spy private EmployeeService employeeService; // Partial mock public EmployeeServiceTest() { MockitoAnnotations.openMocks(this); // Initialize mocks } @Test void testGetEmployeeById_UsingDoReturn() { // Arrange: Use doReturn() to avoid calling the actual method doReturn(new Employee("1", "Mock Employee")).when(employeeService).getEmployeeById("1"); // Act: Call the method Employee employee = employeeService.getEmployeeById("1"); // Assert: Verify the mocked response assertNotNull(employee); assertEquals("1", employee.getId()); assertEquals("Mock Employee", employee.getName()); // Verify the method was called once verify(employeeService, times(1)).getEmployeeById("1"); } } 4. Explanation of doReturn() Why @spy? Spies allow calling real methods unless explicitly mocked. Why doReturn() Instead of when()? when(employeeService.getEmployeeById("1")).thenReturn(...) would still execute the real method (printing "Actual method execution!"). doReturn(...).when(employeeService).getEmployeeById("1") bypasses real execution, ensuring the mock response is returned. 5. Output (Test Execution) Test Passed Successfully! (The real method is not executed, meaning the “Actual method execution!” print statement is avoided.) 6. When to Use doReturn()? Mocking Spies (@spy) to avoid executing real methods. Mocking Final Methods (Mockito allows it, but doReturn() is safer). Mocking Methods That Should Not Be Called (e.g., methods with unwanted side effects like modifying the database). 7. Conclusion Use when().thenReturn() for normal mock objects. Use doReturn().when() for spies or methods that should not execute. Helps prevent unnecessary method execution in tests.

Feb 8, 2025 - 06:56
 0
doReturn() method in Mockito example

Spring Boot Example Using doReturn() in Mockito

The doReturn() method in Mockito is used when you want to mock a method that is already called in a final, private, or spy object, avoiding unwanted method execution.

1. When to Use doReturn() Instead of when()?

Use when().thenReturn() when mocking normal method calls.

Use doReturn().when() when:

Dealing with spies (partial mock objects).
Avoiding unwanted method execution during testing.
Mocking final/private methods indirectly.

  1. Spring Boot Application Code pom.xml


 4.0.0
 
  org.springframework.boot
  spring-boot-starter-parent
  3.4.2
   
 
 com.example
 DoReturnSBProject
 0.0.1-SNAPSHOT
 DoReturnSBProject
 Demo project for Spring Boot
 
 
  
 
 
  
 
 
  
  
  
  
 
 
  17
 
 
  
   org.springframework.boot
   spring-boot-starter-web
  

  
   org.springframework.boot
   spring-boot-starter-test
   test
  
 

 
  
   
    org.springframework.boot
    spring-boot-maven-plugin
   
  
 



Employee.java

package com.example.demo.model;

public class Employee {
    private String id;
    private String name;

    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 Employee getEmployeeById(String id) {
        System.out.println("Actual method execution!"); // Should be avoided in tests
        return new Employee(id, "Real Employee");
    }
}

  1. Unit Test Using doReturn()
package com.example.demo.service;

import com.example.demo.model.Employee;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.mockito.MockitoAnnotations;

import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

class EmployeeServiceTest {

    @Spy
    private EmployeeService employeeService; // Partial mock

    public EmployeeServiceTest() {
        MockitoAnnotations.openMocks(this); // Initialize mocks
    }

    @Test
    void testGetEmployeeById_UsingDoReturn() {
        // Arrange: Use doReturn() to avoid calling the actual method
        doReturn(new Employee("1", "Mock Employee")).when(employeeService).getEmployeeById("1");

        // Act: Call the method
        Employee employee = employeeService.getEmployeeById("1");

        // Assert: Verify the mocked response
        assertNotNull(employee);
        assertEquals("1", employee.getId());
        assertEquals("Mock Employee", employee.getName());

        // Verify the method was called once
        verify(employeeService, times(1)).getEmployeeById("1");
    }
}

4. Explanation of doReturn()

Why @spy?

Spies allow calling real methods unless explicitly mocked.
Why doReturn() Instead of when()?

when(employeeService.getEmployeeById("1")).thenReturn(...) would still execute the real method (printing "Actual method execution!").

doReturn(...).when(employeeService).getEmployeeById("1") bypasses real execution, ensuring the mock response is returned.

5. Output (Test Execution)

Test Passed Successfully!

(The real method is not executed, meaning the “Actual method execution!” print statement is avoided.)

6. When to Use doReturn()?

Mocking Spies (@spy) to avoid executing real methods.
Mocking Final Methods (Mockito allows it, but doReturn() is safer).

Mocking Methods That Should Not Be Called (e.g., methods with unwanted side effects like modifying the database).

7. Conclusion

Use when().thenReturn() for normal mock objects.

Use doReturn().when() for spies or methods that should not execute.

Helps prevent unnecessary method execution in tests.