mockito spiedInstance是破碎的(与间谍相比)还是误导的文件?

时间:2014-07-24 20:36:11

标签: mockito

MockSettings的当前mockito文档页面包含此

Foo foo = mock(Foo.class, withSettings().spiedInstance(fooInstance));
//Below does exactly the same:
Foo foo = spy(fooInstance);

然而,以下快速测试给出了不同的结果:

HashMap<String, String> realMap = new HashMap();
realMap.put("city", "Boston");

HashMap spy1 = spy(realMap);
HashMap spy2 = mock(HashMap.class, withSettings().spiedInstance(realMap));

System.out.println("spy1 city: " + spy1.get("city"));
System.out.println("spy2 city: " + spy2.get("city"));

输出:

spy1 city: Boston
spy2 city: null

我是否误解了某些内容,或者后一种用法是否被破坏(在mockito项目问题页面上没有看到任何内容......)?作为旁注,我的目标是对不熟悉的遗留代码进行一些嘲弄,并希望通过类似

之类的详细记录实现间谍
mock(Foo.class, withSettings.spiedInstance(f).verboseLogging())

任何与mockito一起作为我的工具集的替代方案?

1 个答案:

答案 0 :(得分:4)

很好听。这是一个错误或至少javadoc是错误的。

如果你看一下Mockito.spy源代码:

public static <T> T spy(T object) {
    return MOCKITO_CORE.mock((Class<T>) object.getClass(), withSettings()
            .spiedInstance(object)
            .defaultAnswer(CALLS_REAL_METHODS));
}

您可以轻松解决问题:

Foo foo = mock(Foo.class, withSettings()
           .spiedInstance(fooInstance))
           .defaultAnswer(CALLS_REAL_METHODS);
//Below does exactly the same:
Foo foo = spy(fooInstance);