0

0

Mockito 单元测试中模拟 RestClientException 异常

心靈之曲

心靈之曲

发布时间:2025-09-18 19:00:02

|

919人浏览过

|

来源于php中文网

原创

mockito 单元测试中模拟 restclientexception 异常

本文旨在指导开发者如何在 Mockito 单元测试中模拟 RestClientException 异常。通过模拟 RestTemplate 的 exchange 方法抛出异常,并结合 assertThrows 或 assertThatCode 断言,可以有效地测试服务在遇到外部 API 错误时的处理逻辑,保证程序的健壮性。

在进行单元测试时,我们经常需要模拟外部依赖的行为,以便隔离被测代码并专注于其自身的逻辑。当被测代码依赖于 RestTemplate 调用外部 API 时,模拟 API 调用失败的情况,例如抛出 RestClientException,就显得尤为重要。以下介绍如何在 Mockito 中模拟 RestClientException,并验证异常处理逻辑。

模拟 RestTemplate 抛出 RestClientException

可以使用 doThrow 方法来模拟 RestTemplate 的 exchange 方法抛出 RestClientException。以下是一个示例:

import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;

import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;

import org.junit.jupiter.api.extension.ExtendWith;

@ExtendWith(MockitoExtension.class)
public class IdpFacadeClientTest {

    @Mock
    private RestTemplate restTemplate;

    @InjectMocks
    private IdpFacadeClient idpFacadeClient;

    // 假设的 DTO 类,用于更新记录
    static class UpdateRecordsDto {
        private String firstName;

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
    }

    private String idpFacadeUpdateUrl = "http://example.com/update";


    @Test
    void test_update_customer_in_ath0_server_error(){
        //given
        UpdateRecordsDto updateRecordsDto = new UpdateRecordsDto();
        updateRecordsDto.setFirstName("testFirstName");

        //when
        doThrow(new RestClientException("Idp facade API error"))
                .when(restTemplate).exchange(anyString(), eq(HttpMethod.PATCH), any(HttpEntity.class), eq(String.class));

        //then
        assertThrows(RestClientException.class, () -> idpFacadeClient.updateCustomerFirstNameInIdp(updateRecordsDto));
    }


    private boolean verifyUpdatedCustomerBody(HttpEntity entity) {
        // 实现根据 entity 内容进行验证的逻辑
        return true; // 示例,始终返回 true
    }

    // 模拟的 IdpFacadeClient 类
    class IdpFacadeClient {
        public String updateCustomerFirstNameInIdp(UpdateRecordsDto customerUpdateRecordsDto) {
            String response = null;
            try {
                ResponseEntity restResponse = restTemplate.exchange(idpFacadeUpdateUrl, HttpMethod.PATCH, new HttpEntity<>(customerUpdateRecordsDto),  String.class);
                if (restResponse.getStatusCode() == HttpStatus.OK) {
                    //log.info("customer first name update success {} with status {}", customerUpdateRecordsDto.getFirstName(), response.getStatusCode());
                }else {
                    //log.error("Customer first name update failed in IDP for {} with status {}", customerUpdateRecordsDto.getFirstName(), response.getStatusCode());
                }
            } catch (RestClientException e) {
                throw new RestClientException("Idp facade API error for user first name " + customerUpdateRecordsDto.getFirstName(), e);
            }
            return response;
        }
    }
}

代码解释:

PHP在单元测试中模拟HTTP请求的库
PHP在单元测试中模拟HTTP请求的库

一个在单元测试中模拟HTTP请求的库

下载
  1. @Mock private RestTemplate restTemplate;: 使用 @Mock 注解创建一个 RestTemplate 的 Mock 对象。
  2. @InjectMocks private IdpFacadeClient idpFacadeClient;: 使用 @InjectMocks 注解创建 IdpFacadeClient 的实例,并将 Mock 的 restTemplate 注入到该实例中。
  3. doThrow(new RestClientException("Idp facade API error")) .when(restTemplate).exchange(anyString(), eq(HttpMethod.PATCH), any(HttpEntity.class), eq(String.class));: 使用 doThrow 方法配置 restTemplate 的 exchange 方法,使其在被调用时抛出一个 RestClientException 异常。 anyString()、eq(HttpMethod.PATCH)、any(HttpEntity.class) 和 eq(String.class) 是参数匹配器,用于匹配 exchange 方法的参数。 anyString() 匹配任何字符串类型的 URL。 eq(HttpMethod.PATCH) 匹配 HttpMethod.PATCH 枚举值。 any(HttpEntity.class) 匹配任何 HttpEntity 类型的对象。 eq(String.class) 匹配 String.class 对象。
  4. assertThrows(RestClientException.class, () -> idpFacadeClient.updateCustomerFirstNameInIdp(updateRecordsDto));: 使用 assertThrows 断言来验证 idpFacadeClient.updateCustomerFirstNameInIdp(updateRecordsDto) 方法是否抛出了预期的 RestClientException 异常。

注意事项:

  • 确保在测试类上添加了 @ExtendWith(MockitoExtension.class) 注解,以启用 Mockito 的注解处理器
  • any() 和 eq() 是 Mockito 提供的参数匹配器,用于匹配方法调用的参数。可以根据实际情况选择合适的参数匹配器。
  • 可以使用 assertThrows 或 assertThatCode(…).hasMessageContaining(…) 来验证异常的类型和消息内容。

总结

通过使用 Mockito 的 doThrow 方法,可以方便地模拟 RestTemplate 抛出 RestClientException 异常,从而测试服务在遇到外部 API 错误时的处理逻辑。结合 assertThrows 或 assertThatCode 断言,可以有效地验证异常处理的正确性,提高代码的健壮性和可靠性。在实际开发中,应该充分利用 Mockito 提供的各种功能,编写高质量的单元测试,保证代码的质量。

相关专题

更多
string转int
string转int

在编程中,我们经常会遇到需要将字符串(str)转换为整数(int)的情况。这可能是因为我们需要对字符串进行数值计算,或者需要将用户输入的字符串转换为整数进行处理。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

338

2023.08.02

scripterror怎么解决
scripterror怎么解决

scripterror的解决办法有检查语法、文件路径、检查网络连接、浏览器兼容性、使用try-catch语句、使用开发者工具进行调试、更新浏览器和JavaScript库或寻求专业帮助等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

188

2023.10.18

500error怎么解决
500error怎么解决

500error的解决办法有检查服务器日志、检查代码、检查服务器配置、更新软件版本、重新启动服务、调试代码和寻求帮助等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

288

2023.10.25

js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

258

2023.08.03

js截取字符串的方法
js截取字符串的方法

js截取字符串的方法有substring()方法、substr()方法、slice()方法、split()方法和slice()方法。本专题为大家提供字符串相关的文章、下载、课程内容,供大家免费下载体验。

209

2023.09.04

java基础知识汇总
java基础知识汇总

java基础知识有Java的历史和特点、Java的开发环境、Java的基本数据类型、变量和常量、运算符和表达式、控制语句、数组和字符串等等知识点。想要知道更多关于java基础知识的朋友,请阅读本专题下面的的有关文章,欢迎大家来php中文网学习。

1468

2023.10.24

字符串介绍
字符串介绍

字符串是一种数据类型,它可以是任何文本,包括字母、数字、符号等。字符串可以由不同的字符组成,例如空格、标点符号、数字等。在编程中,字符串通常用引号括起来,如单引号、双引号或反引号。想了解更多字符串的相关内容,可以阅读本专题下面的文章。

620

2023.11.24

java读取文件转成字符串的方法
java读取文件转成字符串的方法

Java8引入了新的文件I/O API,使用java.nio.file.Files类读取文件内容更加方便。对于较旧版本的Java,可以使用java.io.FileReader和java.io.BufferedReader来读取文件。在这些方法中,你需要将文件路径替换为你的实际文件路径,并且可能需要处理可能的IOException异常。想了解更多java的相关内容,可以阅读本专题下面的文章。

550

2024.03.22

Python GraphQL API 开发实战
Python GraphQL API 开发实战

本专题系统讲解 Python 在 GraphQL API 开发中的实际应用,涵盖 GraphQL 基础概念、Schema 设计、Query 与 Mutation 实现、权限控制、分页与性能优化,以及与现有 REST 服务和数据库的整合方式。通过完整示例,帮助学习者掌握 使用 Python 构建高扩展性、前后端协作友好的 GraphQL 接口服务,适用于中大型应用与复杂数据查询场景。

1

2026.01.21

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Django 教程
Django 教程

共28课时 | 3.3万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.2万人学习

Sass 教程
Sass 教程

共14课时 | 0.8万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

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