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
<?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.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>DoReturnSBProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>DoReturnSBProject</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>
<?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.2</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <groupId>com.example</groupId>
 <artifactId>DoReturnSBProject</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>DoReturnSBProject</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>
<?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.2</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>DoReturnSBProject</artifactId> <version>0.0.1-SNAPSHOT</version> <name>DoReturnSBProject</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

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

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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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.

原文链接:doReturn() method in Mockito example

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享
Happiness will never miss any people, sooner or later it will find you.
幸福不会遗漏任何人,迟早有一天它会找到你
评论 抢沙发

请登录后发表评论

    暂无评论内容