当前位置: 首页 > news >正文

Java单元测试Mock的用法,关于接口测试的用例

@Testvoid getAllTradeDateList() {// 创建模拟对象Bc6CalculateService calculateService = Mockito.mock(Bc6CalculateService.class);String allTradeDateListStr = ExcelUtil.excelToJsonStr("bc6/NibTradeDate.xlsx");// 设置模拟行为List<NibTradeDateCloudDto> allTradeDateList = ObjectMapperUtil.parseArray(allTradeDateListStr, NibTradeDateCloudDto.class);Mockito.when(calculateService.getAllTradeDateList()).thenReturn(allTradeDateList);// 执行测试代码List<NibTradeDateCloudDto> testResult = calculateService.getAllTradeDateList();// 验证行为Mockito.verify(calculateService).getAllTradeDateList();// 断言结果assertEquals(allTradeDateList, testResult);}

这段测试代码是一个JUnit测试方法,用于测试Bc6CalculateService类的getAllTradeDateList方法。这里使用了Mockito库来模拟服务层的行为。以下是代码的详细分析:

  1. 方法注解

    • @Test:表示这是一个JUnit测试方法。
  2. 创建模拟对象

    • 使用Mockito.mock(Bc6CalculateService.class)创建了一个Bc6CalculateService的模拟对象calculateService
  3. 准备测试数据

    • 使用ExcelUtil.excelToJsonStr("bc6/NibTradeDate.xlsx")从Excel文件中读取数据,并将其转换为JSON格式的字符串allTradeDateListStr
    • 使用ObjectMapperUtil.parseArray(allTradeDateListStr, NibTradeDateCloudDto.class)将JSON字符串转换为NibTradeDateCloudDto类型的列表allTradeDateList
  4. 设置模拟行为

    • 使用Mockito.when(calculateService.getAllTradeDateList()).thenReturn(allTradeDateList);设置当调用calculateServicegetAllTradeDateList方法时,返回预设的allTradeDateList列表。
  5. 执行测试代码

    • 调用calculateService.getAllTradeDateList()方法,并将返回的结果存储在testResult中。由于calculateService是一个模拟对象,并且我们已经设置了它的行为,因此它会返回我们在第4步中设置的allTradeDateList
  6. 验证行为

    • 使用Mockito.verify(calculateService).getAllTradeDateList();来验证getAllTradeDateList方法确实被调用了一次。
  7. 断言结果

    • 使用assertEquals(allTradeDateList, testResult);来断言testResult(从模拟对象获取的结果)与allTradeDateList(预设的期望结果)是否相等。

整体来说,这个测试方法的目的是确保Bc6CalculateServicegetAllTradeDateList方法能够正确地返回一个与预期结果相同的NibTradeDateCloudDto列表。如果getAllTradeDateList方法的实际实现与测试中的模拟行为不一致,或者返回的结果与期望的结果不匹配,那么测试将会失败。

http://www.lryc.cn/news/356912.html

相关文章:

  • 《心理学报》文本分析技术最新进展总结盘点
  • json格式文件备份redis数据库 工具
  • JAVA系列:NIO
  • 偏微分方程算法之抛物型方程差分格式编程示例二
  • linux 查看 线程名, 线程数
  • python class __getattr__ 与 __getattribute__ 的区别
  • [ C++ ] 类和对象( 下 )
  • 这么多不同接口的固态硬盘,你选对了嘛!
  • 使用IDEA远程debug调试
  • 开源自定义表单系统源码 一键生成表单工具 可自由DIY表单模型+二开
  • 【java10】集合中新增copyof创建只读集合
  • python小甲鱼作业001-3讲
  • 做电商,错过了2020年的抖音!那2024一定要选择视频号小店!
  • 赛氪网与武汉外语外事职业学院签署校企合作,共创职业教育新篇章
  • 如何在文档中有效添加网格:技巧与实例
  • 设计模式10——装饰模式
  • 如果返回的json 中有 ‘///’ 转换
  • JAVA学习-练习试用Java实现“多线程问题”
  • SQOOP详细讲解
  • 【Unity入门】认识Unity编辑器
  • Spring控制重复请求
  • AWS安全性身份和合规性之Key Management Service(KMS)
  • esp32 固件备份 固件恢复
  • linux开发之设备树四、设备树中断节点
  • 基于STM32实现智能楼宇对讲系统
  • 面试专区|【DevOps-46道DevOps高频题整理(附答案背诵版)】
  • 算法基础之台阶-Nim游戏
  • VUE3注册指令的方法
  • 【Python】 Python 字典查询:‘has_key()‘ 方法与 ‘in‘ 关键字的比较
  • IDEA通过tomcat运行注意事项