java - 如何测试是否将正确的 lambda 值作为参数传递(使用 Mockito)?
问题描述
我有这个功能:
public class Cache {
(...)
public void removeAllIf(Predicate<Product> predicate) {
(...)
}
}
我打电话给productsCache.removeAllIf(Product::isChecked);
目前我用
then(productsCache).should().removeAllIf(any(Predicate.class));
但这不准确(不测试传递的 lambda 是否为Product::isChecked
)。第二个问题是我收到 lint 消息:Unchecked assignment。
它是更好的解决方案吗?
编辑:
我不想测试removeAllIf
功能实现。我想测试是否removeAllIf
使用正确的参数调用。
要测试的场景:
public class Repository {
public void removeCheckedProducts() {
remoteDataSource.removeCheckedProducts();
localDataSource.removeCheckedProducts();
cache.removeAllIf(Product::isChecked);
}
}
单元测试:
@Test
public void removeCheckedProducts() {
//when
repository.removeCheckedProducts();
//then
then(remoteDataSource).should().removeCheckedProducts();
then(localDataSource).should().removeCheckedProducts();
then(cache).should().removeAllIf(any(Predicate.class));
}
解决方案
您可以使用 ArgumentCaptor
@Captor
ArgumentCaptor<Predicate> captor = ArgumentCaptor.forClass(Predicate.class);;
@Test
public void removeCheckedProducts() {
//when
repository.removeCheckedProducts();
//then
then(remoteDataSource).should().removeCheckedProducts();
then(localDataSource).should().removeCheckedProducts();
then(cache).should().removeAllIf(captor.capture());
Predicate t = Product.checkPredicate();
assertSame(t,captor.getValue());
}
推荐阅读
- mongodb - 使用 mongodb (3.4) 在一个数据库调用中执行两个不同的操作
- vue.js - Vuex 计算属性中的 getter / setter 语法错误
- typescript - 打字稿:语法错误。意外的标记
- selenium-webdriver - 我想将普通 selenium Webdriver Java 脚本转换为 Katalon Studio 脚本
- javascript - 反应 redux 状态未定义
- perl - 检查在 Perl 中附加字符串的两种方法的性能
- r - R 3.5,Ubuntu 18.04,错误:无法与 R 会话建立连接
- chronicle - 从 Bytes 中检索 ByteBuffer 对象
- spring-mvc - 如何使用 thymeleaf 包含外部 javascript 文件?
- python-3.x - 如何删除熊猫列中的单词