Java 8中如何基于参数对象的字段Mock方法行为?
实现方案
当然可以实现,以下是两种常用的实现方式:
方式一:通过thenAnswer自定义返回逻辑
利用thenAnswer获取调用时的参数,手动判断字段值后返回对应结果:
// 请根据performExecution实际返回类型调整返回值类型 when(myClass.performExecution(any(ParamsClass.class))).thenAnswer(invocation -> { ParamsClass params = invocation.getArgument(0); // 注意:ParamsClass需要提供getField1()方法来访问私有字段 if ("1".equals(params.getField1())) { return "特定响应"; } else { return "其他响应"; } });
方式二:使用argThat参数匹配器
通过参数匹配器指定符合条件的参数,分别配置不同返回结果:
// 匹配field1值为"1"的ParamsClass对象,返回特定响应 when(myClass.performExecution(argThat(params -> "1".equals(params.getField1())))) .thenReturn("特定响应"); // 匹配所有其他ParamsClass对象,返回默认响应 when(myClass.performExecution(any(ParamsClass.class))) .thenReturn("其他响应");
注意事项
- 必须确保
ParamsClass提供getField1()方法,因为私有字段无法直接在外部访问;如果没有getter,可通过反射获取字段值(不推荐,建议为测试场景添加getter方法)。 - Mockito 3及以上版本支持直接在
argThat中使用lambda表达式,无需额外适配。
内容的提问来源于stack exchange,提问作者GlidingSwords997
相关产品推荐
相关产品推荐

