登录
首页 >  文章 >  java教程

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

时间:2025-02-02 22:00:53 423浏览 收藏

哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《莫科托示例中的thenthrow()方法》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!

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

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

1. Spring Boot 应用代码

  • Employee.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 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()方法》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>