当前位置:首页 > 文章列表 > 文章 > java教程 > Mockito 示例中的 thenReturn() 方法

Mockito 示例中的 thenReturn() 方法

2025-01-28 16:48:49 0浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《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;

@Service
public 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;

@RestController
public 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. 测试流程

测试方法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() 方法》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

王元琳任荣耀中国区总裁王元琳任荣耀中国区总裁
上一篇
王元琳任荣耀中国区总裁
森霸传感:公司实际控制人、董事长单森林被留置
下一篇
森霸传感:公司实际控制人、董事长单森林被留置
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    543次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    516次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    500次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    485次学习
查看更多
AI推荐
  • PubMedQA数据集详解:生物医学问答基准、功能与应用指南
    PubMedQA
    深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
    185次使用
  • H2O EvalGPT:开源LLM大模型评估与排行榜工具
    H2O EvalGPT
    H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
    241次使用
  • LMArena是什么?伯克利AI模型评估平台使用指南与功能解析
    LMArena
    LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
    197次使用
  • 斯坦福HELM:大语言模型Holistic Evaluation整体评估框架详解
    HELM
    深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
    178次使用
  • CMMLU中文大模型评估基准:功能、使用教程与应用场景解析
    CMMLU
    深入了解CMMLU中文评估基准,涵盖67个学科主题,提供数据集下载、Zero-shot/Five-shot评估方法及排行榜,助力优化中文语言模型性能。
    170次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码