【发布时间】:2023-03-12 23:20:01
【问题描述】:
我有以下要模拟的 Logger,但要验证日志条目是否被调用,而不是内容。
private static Logger logger =
LoggerFactory.getLogger(GoodbyeController.class);
我想模拟用于 LoggerFactory.getLogger() 的任何类,但我不知道该怎么做。 到目前为止,这就是我的最终结果:
@Before
public void performBeforeEachTest() {
PowerMockito.mockStatic(LoggerFactory.class);
when(LoggerFactory.getLogger(GoodbyeController.class)).
thenReturn(loggerMock);
when(loggerMock.isDebugEnabled()).thenReturn(true);
doNothing().when(loggerMock).error(any(String.class));
...
}
我想知道:
- 我可以模拟静态
LoggerFactory.getLogger()来为任何班级工作吗? - 我似乎只能在
@Before中运行when(loggerMock.isDebugEnabled()).thenReturn(true);,因此我似乎无法更改每个方法的特征。有没有办法解决这个问题?
编辑结果:
我以为我已经尝试过了,但没有成功:
when(LoggerFactory.getLogger(any(Class.class))).thenReturn(loggerMock);
但是谢谢你,因为它确实有效。
但是我已经尝试了无数种变化:
when(loggerMock.isDebugEnabled()).thenReturn(true);
我无法让 loggerMock 在 @Before 之外更改其行为,但这仅发生在 Coburtura 上。使用 Clover,覆盖率显示为 100%,但无论哪种方式仍然存在问题。
我有这个简单的课程:
public ExampleService{
private static final Logger logger =
LoggerFactory.getLogger(ExampleService.class);
public String getMessage() {
if(logger.isDebugEnabled()){
logger.debug("isDebugEnabled");
logger.debug("isDebugEnabled");
}
return "Hello world!";
}
...
}
然后我有这个测试:
@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFactory.class})
public class ExampleServiceTests {
@Mock
private Logger loggerMock;
private ExampleServiceservice = new ExampleService();
@Before
public void performBeforeEachTest() {
PowerMockito.mockStatic(LoggerFactory.class);
when(LoggerFactory.getLogger(any(Class.class))).
thenReturn(loggerMock);
//PowerMockito.verifyStatic(); // fails
}
@Test
public void testIsDebugEnabled_True() throws Exception {
when(loggerMock.isDebugEnabled()).thenReturn(true);
doNothing().when(loggerMock).debug(any(String.class));
assertThat(service.getMessage(), is("Hello null: 0"));
//verify(loggerMock, atLeast(1)).isDebugEnabled(); // fails
}
@Test
public void testIsDebugEnabled_False() throws Exception {
when(loggerMock.isDebugEnabled()).thenReturn(false);
doNothing().when(loggerMock).debug(any(String.class));
assertThat(service.getMessage(), is("Hello null: 0"));
//verify(loggerMock, atLeast(1)).isDebugEnabled(); // fails
}
}
在三叶草中,我显示了 if(logger.isDebugEnabled()){ 块的 100% 覆盖率。
但是如果我尝试验证loggerMock:
verify(loggerMock, atLeast(1)).isDebugEnabled();
我得到零互动。
我也试过PowerMockito.verifyStatic();在@Before 中,但也有零交互。
Cobertura 将if(logger.isDebugEnabled()){ 显示为不是 100% 完成,这似乎很奇怪,而 Clover 确实如此,但两者都同意验证失败。
【问题讨论】:
-
你试过@MockPolicy吗? Examples here 用于 EasyMock 风格的模拟,但可以适用于 Mockito。
标签: java junit mockito slf4j powermock