unit-testing - 在 spring + Mockito 中模拟传递的功能接口
问题描述
我正在为作为行为传递的方法创建测试,我不确定模拟如何用于功能性。我不想模拟executeBehaviour调用,而是模拟行为 function.apply 的实际执行
public String processData(){
String a="check";
return executeBehaviour((check)->"hello"+check,a);
}
public String executeBehaviour(Function<String,String> data,String data1){
//Some processing
return data.apply(data1);
}
我已经编写了以下测试用例,但它似乎没有模拟 data.apply() 调用。测试用例:
@Test
void sampleTest() {
Function<String, String> processFunction = mock(Function.class);
String test = "check";
when(groupingFunction.apply(anyString())).thenReturn(test);
String data = itemInventoryProcessorService.executeBehaviour(processFunction,test);
Assertions.assertEquals("check", data);
}
断言失败,因为写入的数据是实际执行的行为,即“hellocheck”而不是模拟的“check”。
解决方案
使用 doAnswer,我们可以提供函数的实现并返回我们正在尝试验证的假/存根结果。通过这种方式,我们基本上是自己为函数提供了一个存根。
@Test
void sampleTest() {
String test = "check";
doAnswer(invocation -> {
Function<String, String> processingFunction = invocation.getArgument(0);
groupingFunction.apply("dummy");
return test;
}).when(itemInventoryProcessorService). executeBehaviour(any(Function.class), anyString());
var data = itemInventoryProcessorService. processData();
Assertions.assertEquals("check", data);
}
推荐阅读
- c# - “未找到元素。” 引发 PropertyChanged UWP Xamarin 时出错
- pyspark - 在 pyspark 中写入输出 Json 文件时缺少列
- python - 将列表转换为数据框,选择一些特定元素作为列名
- mongodb - 分片数据集群中的 StaleConfig 错误,由于检测到 db.collection_name 的版本不匹配导致集群数据放置更改错误”
- java - Artemis SOCKS 代理支持
- firebase - Flutter Web Firebase TypeError:dart.global.firebase.firestore 不是函数
- apache-camel - 升级到camel set of jars 3.x 失败,ActiveMQDestination 出现 ClassNotFoundException
- python - Errno 111:使用 Python 脚本连接到 Elasticsearch 时连接被拒绝
- ios - 从 UITableView 获取所有单元格
- html - 如何让项目符号点显示在 HTML 选项卡中