Java单元测试Mock接口模拟调用其中某个方法

java 复制代码
@Test
void bondCalculate() {
	Bc6CalculateRequestDto requestDto = new Bc6CalculateRequestDto();
	requestDto.setTradeDate(LocalDate.now());
	requestDto.setSpeed(SpeedEnum.T_1.getSpeed());
	requestDto.setCalcType(Strings.concat(ModifyFieldEnum.RATE.getField(), ModifyFieldEnum.FIRST_AMOUNT.getField()));
	//
	Bc6CalculateServiceImpl bc6CalculateService = Mockito.spy(new Bc6CalculateServiceImpl());
	String allTradeDateListStr = ExcelUtil.excelToJsonStr("bc6/NibTradeDate.xlsx");
	List < NibTradeDateCloudDto > allTradeDateList = ObjectMapperUtil.parseArray(allTradeDateListStr, NibTradeDateCloudDto.class);
	Mockito.doReturn(allTradeDateList).when(bc6CalculateService).getAllTradeDateList();
	//
	Bc6CalcResponseDto responseDto = bc6CalculateService.bondCalculate(requestDto);
	System.out.println(responseDto.toString());
}

这个测试方法模拟了 Bc6CalculateService 的一个实例,并试图测试 bondCalculate 方法。它使用了 Mockito.spy 来创建一个真实对象的部分模拟(间谍),并模拟了 getAllTradeDateList 方法的行为。然后,它调用了 bondCalculate 方法并打印了返回的 Bc6CalcResponseDto 对象的字符串表示。

相关推荐
武子康几秒前
AI研究-133 Java vs Kotlin/Go/Rust/Python/Node:2025 详细对比分析 定位与取舍指南
java·javascript·python·golang·rust·kotlin·node
k***92163 分钟前
Spring Boot(七):Swagger 接口文档
java·spring boot·后端
执笔论英雄5 分钟前
【RL]expand_requests干啥的
服务器·开发语言·python
kesifan6 分钟前
JAVA线程的建立方法
java·开发语言·python
周杰伦fans7 分钟前
C#中ValueTask
开发语言·c#
qq_336313939 分钟前
java基础-set类集合进阶
java·算法
菠菠萝宝12 分钟前
【Java手搓OpenManus】-5- 工具系统设计
java·开发语言·人工智能·openai·agent·manus
d***93517 分钟前
Spring Boot 自动配置
java·spring boot·后端
h***673718 分钟前
Spring Boot文件上传
java·spring boot·后端
kyle~18 分钟前
数据结构---堆(Heap)
服务器·开发语言·数据结构·c++