java - 用 mockito 监视 lambda
问题描述
在编写涉及模拟 lambda 的单元测试时,我遇到了一个有趣的问题。
@Test
public void spyingLambda() {
final Supplier<String> spy = Mockito.spy((Supplier) () -> "1");
spy.get();
}
运行此测试失败并出现以下错误:
Mockito 无法模拟/监视,因为:-final class
上述问题的一种解决方法是用匿名实现替换 lambda:
@Test
public void spyingAnonymousImplementation() {
final Supplier<String> spy = Mockito.spy(new Supplier<String>() {
@Override
public String get() {
return "1";
}
});
spy.get();
}
尽管两个测试完全相同(IDE 建议甚至用 lambda 替换匿名实现),但第二个测试并没有失败。
我想知道这是否是可以在 mockito 中修复的已知问题,或者是否有任何其他解决方法。
解决方案
处理此问题的另一种方法如下:
/**
* This method overcomes the issue with the original Mockito.spy when passing a lambda which fails with an error
* saying that the passed class is final.
*/
public static <T> T spyLambda(final Class<T> lambdaType, final T lambda) {
return mock(lambdaType, delegatesTo(lambda));
}
它允许通过更改第一种方法来监视 lambda,如下所示:
@Test
public void spyingLambda() {
final Supplier<String> spy = spyLambda(Supplier.class, () -> "1");
spy.get();
}
希望以上示例可以帮助遇到相同问题的其他人。
推荐阅读
- php - DBAL QueryBuilder:避免 SQL 注入的更安全的方法是什么?
- java - JAVA:在 ArrayList 中添加“Shape”类型的对象?
- java - 在 java multi-catch 中,每个 multi-catch 字符都是最终的,但我无法得到它
- php - Laravel 6 表单数组验证
- reactjs - React Material - MUIDataTable - 如何在列标题中添加内容
- swift - Wy md5 hash 使用 swift 给了我不同的结果
- python - input_sentences = [text.split("") for text in df["text"].values.tolist()]
- flutter - Flutter - NoSuchMethodError:在 null 上调用了 getter 'focusScopeNode'
- deployment - 部署 ARM 后自托管 IR 不可用
- math - 计算颤动中的价格折扣