首页 > 解决方案 > 用 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 中修复的已知问题,或者是否有任何其他解决方法。

标签: javaunit-testinglambdamockito

解决方案


处理此问题的另一种方法如下:

/**
 * 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();
}

希望以上示例可以帮助遇到相同问题的其他人。


推荐阅读