Mocking Logger and LoggerFactory with PowerMock and Mockito
我有以下记录器,我想模拟出来,但要验证日志条目被调用,而不是内容。
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()
- 我似乎只能在 中运行,因此我似乎无法更改每个方法的特征。有没有办法解决这个问题?when(loggerMock.isDebugEnabled()).thenReturn(true);@Before
编辑结果:
我以为我已经尝试过了,但它不起作用:
 when(LoggerFactory.getLogger(any(Class.class))).thenReturn(loggerMock);
但是谢谢你,因为它确实有效。
但是,我已经尝试了无数的变体:
when(loggerMock.isDebugEnabled()).thenReturn(true);
我无法让loggerMock在外面改变它的行为,但这只发生在Coburtura身上。对于三叶草,覆盖率显示为100%,但无论哪种方式仍然存在问题。@Before
我有这个简单的类:
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
    }
}
在三叶草中,我显示了100%的块覆盖率。但是,如果我尝试验证:if(logger.isDebugEnabled()){loggerMock
verify(loggerMock, atLeast(1)).isDebugEnabled();
我没有得到任何互动。我也试过了;但那也有零相互作用。PowerMockito.verifyStatic()@Before
这似乎很奇怪,Cobertura表明它不是100%完整的,而Clover确实如此,但两者都同意验证失败。if(logger.isDebugEnabled()){
 
					 
				 
				    		 
				    		 
				    		 
				    		