我无法模拟接口中定义为默认方法的方法。有人可以帮我吗?
该界面具有提供记录器的默认方法。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public interface Loggable {
default Logger logger() {
return LoggerFactory.getLogger(this.getClass());
}
}
以这种方式使用:
public class AppShowOff implements Loggable{
public void doMagic() {
logger().debug("It works");
System.out.println("Works");
}
}
现在我想编写一个测试来证明已调用了调试方法。
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.mockito.Mockito;
import org.slf4j.Logger;
public class AppShowOffTest {
@Test
public void doMagic() {
Logger loggerMock = mock(Logger.class);
Loggable loggableMock = mock(Loggable.class); // <- not needed, but I also tried this way
// mocks done
AppShowOff app = new AppShowOff();
AppShowOff appSpy = Mockito.spy(new AppShowOff());
when(loggableMock.logger()).thenReturn(loggerMock);
when(appSpy.logger()).thenReturn(loggerMock);
app.doMagic();
verify(loggerMock, times(1)).debug(any());
}
}
如您所见,我尝试通过两种方式模拟默认方法:
when(loggableMock.logger()).thenReturn(loggerMock);
when(appSpy.logger()).thenReturn(loggerMock);
但不起作用。结果是:
希望但未调用:logger.debug(); ->这样。AppShowOffTest.doMagic(AppShowOffTest.java:29)实际上,与该模拟的交互为零。
答案 0 :(得分:0)
这里:
AppShowOff app = new AppShowOff();
AppShowOff appSpy = Mockito.spy(new AppShowOff());
除了调用被测方法app
之外,从不使用第一个doMagic()
...。
简单的答案:完全丢弃app
,然后调用appSpy.doMagic()
。