【发布时间】:2012-11-08 15:06:39
【问题描述】:
我正在使用 Mockito 模拟一个对象,该对象上的相同方法被多次调用,我希望每次都返回相同的值。
这就是我所拥有的:
LogEntry entry = null; // this is a field
// This method is called once only.
when(mockLogger.createNewLogEntry()).thenAnswer(new Answer<LogEntry>() {
@Override
public LogEntry answer(InvocationOnMock invocationOnMock) throws Throwable {
entry = new LogEntry();
return entry;
}
});
// This method can be called multiple times,
// If called after createNewLogEntry() - should return initialized entry.
// If called before createNewLogEntry() - should return null.
when(mockLogger.getLogEntry()).thenAnswer(new Answer<LogEntry>() {
@Override
public LogEntry answer(InvocationOnMock invocationOnMock) throws Throwable {
return entry;
}
});
问题是,我的 getLogEntry 方法似乎只被调用了一次。对于所有后续调用,null 会改为返回,我会在测试中获得 NPE。
如何告诉 mockito 对所有调用使用存根版本?
================================================ ==================
为后代验尸
我做了一些额外的调查,一如既往,这不是图书馆的错,而是我的错。在我的代码中,在调用createNewLogEntry() 之前调用getLogEntry() 的方法之一。 NPE 绝对合法,测试实际上是在我的代码中发现了一个错误,而不是我在 Mockito 中发现了错误。
【问题讨论】:
-
相当神秘。通常,这应该有效。我想我会提出几个问题:1)你确定它是空的条目,而不是以某种方式将 mockLogger 重置为空吗? 2)是否有可能在没有模拟方法的情况下重新创建 mockLogger?在定义它的方法(设置与测试方法)中构建上述代码可能会有所帮助。最后,您可以在答案 impl(或断点)中尝试 println,以确保实际执行的是什么。
-
试图重现您的问题,使用 Mockito 1.9.5 的类似方法适用于我 ==> 也许您可以通过 Mockito 邮件列表发送整个 Test 类的代码?
标签: java unit-testing junit mocking mockito