使用Mockito 对方法中的私有void方法,以及本类中的公共方法
这里用一段代码举例
public void ruleJudgement(Long tenantId, Long productId, Long equipId, List<ModelAttributeValue> modelAttributeValues, List<EquipReportValue> equipReportValues) {
//这里是一些正常的方法
// 这个是需要moke的私有方法
executeAction(ruleId);
//这个是需要moke的本类公共方法
SysDictTypeVO dictType = selectDictTypeById(dictId);
}
}
public SysDictTypeVO selectDictTypeById(Long dictId) {
//正常业务
}
private void executeAction(Long ruleId) {
//又一个私有方法
setFunctionRecordJson(modelFunctionRecord, rule.getDeptId());
}
private void setFunctionRecordJson(ModelFunctionRecord functionRecord, Long tenantId) {
//正常业务
}
下面就是test测试方法
@Test
public void ruleJudgementTest() throws Exception{
//RuleJudgmentServiceImpl这个是你自己moke的那个类的名字
RuleJudgmentServiceImpl spy = PowerMockito.spy(ruleJudgmentService);
//这个是你moke的那个公共方法
spy.ruleJudgement(11L,12L,13L,list,valueList);
//第一个参数是你的私有方法名字,第二个参数就是你私有方法的参数
PowerMockito.verifyPrivate(spy).invoke("setFunctionRecordJson",modelFunctionRecord,789L);
PowerMockito.verifyPrivate(spy).invoke("executeAction",123L);
//创建返回值需要的参数
SysDictTypeVO sysDictTypeVO = new SysDictTypeVO();
sysDictTypeVO.setDictType("1");
//第一个参数是你方法的返回类型,第二个参数是上面创建的moke类别名,然后就是方法名跟上参数
Mockito.doReturn(sysDictTypeVO).when(spy).selectDictTypeById(anyLong());
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构