我用Mockito嘲笑一个对象,这个对象上的同一个方法被多次调用,我想每次都返回相同的值。
这是我有: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对所有呼叫使用stubbed版本?
============================================== ===================
验尸子孙后代
我做了一些额外的调查,并一如既往它不是图书馆的错,是我的错。在我的代码之前调用createNewLogEntry()
之前调用getLogEntry()
的方法之一。 NPE是绝对合法的,测试实际上在我的代码中发现了一个错误,而不是我在Mockito中发现错误。
很神秘。一般来说,这应该起作用。我想我会提出几个问题:1)你确定它是空的条目,而不是以某种方式将mockLogger重置为空吗? 2)是否有可能mockLogger正在重新创建没有嘲笑的方法?在定义它的方法中设置上面的代码(安装与测试方法)可能会有所帮助。最后,你可以在你的答案impl(或断点)中试试println,以确定实际执行的是什么。 –
试图重现你的问题,类似的方法适用于我使用Mockito 1.9.5 ==>也许你可以通过Mockito邮件列表发送整个测试类的代码? – s106mo