Mockito 示例中的 thenReturn() 方法

mockito 示例中的 thenreturn() 方法

本文演示如何使用Mockito的thenReturn()方法模拟服务来测试Spring Boot控制器。我们将创建一个简单的员工管理系统,包含Employee实体类、EmployeeService服务类和EmployeeController控制器类,并编写单元测试来验证控制器的功能。

1. 代码示例

Employee.java (实体类):

package com.example.demo.model;public class Employee {    private String id;    private String name;    // constructors, 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;@Servicepublic class EmployeeService {    public Employee getEmployeeById(String id) {        // 模拟从数据库获取员工信息        return new Employee(id, "Default Name");    }}

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.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class EmployeeController {    private final EmployeeService employeeService;    public EmployeeController(EmployeeService employeeService) {        this.employeeService = employeeService;    }    @GetMapping("/employees/{id}")    public Employee getEmployee(@PathVariable String id) {        return employeeService.getEmployeeById(id);    }}

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.junit.jupiter.api.extension.ExtendWith;import org.mockito.InjectMocks;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;import static org.junit.jupiter.api.Assertions.*;import static org.mockito.Mockito.*;@ExtendWith(MockitoExtension.class) // 使用Mockito扩展class EmployeeControllerTest {    @Mock    private EmployeeService employeeService;    @InjectMocks    private EmployeeController employeeController;    @Test    void testGetEmployee() {        // Arrange: 使用when().thenReturn()模拟服务行为        when(employeeService.getEmployeeById("1")).thenReturn(new Employee("1", "John Doe"));        // Act: 调用控制器方法        Employee employee = employeeController.getEmployee("1");        // Assert: 验证返回的对象        assertNotNull(employee);        assertEquals("1", employee.getId());        assertEquals("John Doe", employee.getName());        // 验证模拟的服务是否被调用        verify(employeeService, times(1)).getEmployeeById("1");    }}

2. when().thenReturn() 的作用

when(employeeService.getEmployeeById("1")).thenReturn(new Employee("1", "John Doe")); 这行代码使用Mockito的when()方法指定当employeeService.getEmployeeById("1")被调用时,应该返回一个新的Employee对象,其ID为”1″,姓名为”John Doe”。这模拟了服务从数据库获取员工信息的场景。

3. 测试流程

法语写作助手 法语写作助手

法语助手旗下的AI智能写作平台,支持语法、拼写自动纠错,一键改写、润色你的法语作文。

法语写作助手 31 查看详情 法语写作助手

测试方法testGetEmployee包含三个步骤:

Arrange (准备): 使用when().thenReturn()设置模拟服务的返回值。Act (执行): 调用employeeController.getEmployee("1")方法。Assert (断言): 使用assertNotNull()assertEquals()验证返回的Employee对象是否符合预期,并使用verify()验证employeeService.getEmployeeById("1")方法是否被调用了一次。

4. 依赖注入和验证

@Mock注解用于创建EmployeeService的模拟对象,@InjectMocks注解将模拟的EmployeeService注入到EmployeeController中。verify()方法用于验证模拟对象的方法调用次数,确保测试覆盖了预期的代码路径。

通过这个例子,您可以理解如何在Spring Boot应用中使用Mockito的thenReturn()方法来模拟服务,并编写有效的单元测试,从而提高代码质量和可维护性。 无需启动整个Spring Boot应用,就能测试控制器的逻辑。

以上就是Mockito 示例中的 thenReturn() 方法的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/284277.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年11月4日 17:48:13
下一篇 2025年11月4日 17:53:05

相关推荐

发表回复

登录后才能评论
关注微信