Ula*_*kar 11 java junit unit-testing mocking 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;
}
});
Run Code Online (Sandbox Code Playgroud)
问题是,似乎我的getLogEntry方法只被调用一次.对于所有后续调用,null将返回,我将在测试中获得NPE.
如何告诉mockito使用存根版本进行所有通话?
================================================== ===============
为后代验尸
我做了一些额外的调查,一如既往不是图书馆的错,这是我的错.在我的代码中调用getLogEntry()之前调用的方法之一createNewLogEntry().NPE绝对合法,测试实际上在我的代码中发现了一个错误,而不是我在Mockito中发现错误.