我有以下Logger我想模擬出來,但是驗證日誌條目是被調用的,而不是內容。使用PowerMock和Mockito嘲笑Logger和LoggerFactory
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改變@Before
以外的行爲,但這只是與Coburtura發生。使用三葉草,覆蓋率顯示爲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嗎? [示例](https://code.google.com/p/powermock/wiki/MockPolicies)適用於EasyMock風格的嘲笑,但可以適用於Mockito。 –