首页 > Java > java教程 > 正文

莫科托示例中的thenthrow()方法

心靈之曲
发布: 2025-02-01 18:22:01
原创
1050人浏览过

莫科托示例中的thenthrow()方法

方案:模拟服务异常以测试控制器中的错误处理

1. Spring Boot 应用代码

  • 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;
    }
}
登录后复制
  • EmployeeNotFoundException.java
package com.example.demo.exception;

public class EmployeeNotFoundException extends RuntimeException {
    public EmployeeNotFoundException(String message) {
        super(message);
    }
}
登录后复制
  • EmployeeService.java
package com.example.demo.service;

import com.example.demo.exception.EmployeeNotFoundException;
import com.example.demo.model.Employee;
import org.springframework.stereotype.Service;

@Service
public class EmployeeService {
    public Employee getEmployeeById(String id) {
        // 模拟员工不存在时抛出异常
        if ("0".equals(id)) {
            throw new EmployeeNotFoundException("Employee not found with id: " + id);
        }
        return new Employee(id, "John Doe");
    }
}
登录后复制
  • EmployeeController.java
package com.example.demo.controller;

import com.example.demo.exception.EmployeeNotFoundException;
import com.example.demo.model.Employee;
import com.example.demo.service.EmployeeService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/employees")
public class EmployeeController {
    private final EmployeeService employeeService;

    public EmployeeController(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    @GetMapping("/{id}")
    public ResponseEntity<Employee> getEmployee(@PathVariable String id) {
        Employee employee = employeeService.getEmployeeById(id);
        return ResponseEntity.ok(employee);
    }

    // 全局异常处理
    @ExceptionHandler(EmployeeNotFoundException.class)
    public ResponseEntity<String> handleEmployeeNotFoundException(EmployeeNotFoundException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
    }
}
登录后复制

2. 使用 thenThrow() 的单元测试

  • EmployeeControllerTest.java
package com.example.demo.controller;

import com.example.demo.exception.EmployeeNotFoundException;
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 org.springframework.http.ResponseEntity;

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

class EmployeeControllerTest {

    @Mock
    private EmployeeService employeeService;

    @InjectMocks
    private EmployeeController employeeController;

    public EmployeeControllerTest() {
        MockitoAnnotations.openMocks(this); // 初始化 Mock 对象
    }

    @Test
    void testGetEmployee_Success() {
        // Arrange: 模拟服务方法返回一个 Employee 对象
        when(employeeService.getEmployeeById("1")).thenReturn(new Employee("1", "John Doe"));

        // Act: 调用控制器方法
        ResponseEntity<Employee> response = employeeController.getEmployee("1");

        // Assert: 验证响应是否正确
        assertNotNull(response);
        assertEquals(200, response.getStatusCodeValue());
        assertEquals("John Doe", response.getBody().getName());

        // 验证服务方法被调用了一次
        verify(employeeService, times(1)).getEmployeeById("1");
    }

    @Test
    void testGetEmployee_ThrowsException() {
        // Arrange: 模拟服务方法抛出异常
        when(employeeService.getEmployeeById("0")).thenThrow(new EmployeeNotFoundException("Employee not found with id: 0"));

        // Act & Assert: 验证异常是否被正确处理
        assertThrows(EmployeeNotFoundException.class, () -> {
            employeeController.getEmployee("0");
        });

        // 验证服务方法被调用了一次
        verify(employeeService, times(1)).getEmployeeById("0");
    }
}
登录后复制

说明:

thenThrow() 的用法:when(employeeService.getEmployeeById("0")).thenThrow(new EmployeeNotFoundException("Employee not found with id: 0")); 这行代码模拟了当 getEmployeeById 方法传入 "0" 时抛出 EmployeeNotFoundException 异常。

单元测试包含两个测试用例:

  • testGetEmployee_Success: 测试成功获取员工信息的情况。
  • testGetEmployee_ThrowsException: 测试员工不存在,服务抛出异常的情况,并验证异常被正确处理。

thenThrow() 的优点:

  • 模拟真实世界的错误处理,无需修改实际服务代码。
  • 方便测试各种异常场景,例如数据库错误、数据丢失、API 失败等。
  • 确保在发生错误时,应用返回正确的响应。

结论:

使用 Mockito 的 thenThrow() 方法,可以有效地测试异常处理逻辑,而无需依赖实际的服务实现。 这使得单元测试更加简洁、可靠,并且易于维护。

以上就是莫科托示例中的thenthrow()方法的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号