我想單元測試在我的代碼中生成的日誌語句。我正在使用slfj,log4j和Mockito。我現在用的是類似的代碼如下從博客在 http://bloodredsun.com/2010/12/09/checking-logging-in-unit-tests/運行單元測試時未調用Mockito模擬log4j appender
當我運行它拋出異常的測試說,有0調用在行:
verify(mockAppender).doAppend(captorLoggingEvent.capture());
錯誤消息:
通緝但未調用:mockAppender.doAppend(); - > at testClass.testLogAdviceAfterReturning(DpsOpsLoggerTest2.java:94)實際上,這個模擬與零交互。
我看到控制檯上打印的日誌。請求您提供幫助。
@RunWith(MockitoJUnitRunner.class)
public class ExampleThatLogsTest {
@Mock
private Appender mockAppender;
@Captor
private ArgumentCaptor captorLoggingEvent;
@Before
public void setup() {
LogManager.getRootLogger().addAppender(mockAppender);
}
@After
public void teardown() {
LogManager.getRootLogger().removeAppender(mockAppender);
}
@Test
public void shouldConcatAndLog() {
//given
ExampleThatLogs example = new ExampleThatLogs();
//when
String result = example.concat("foo", "bar");
//then
assertEquals("foobar", result);
verify(mockAppender).doAppend(captorLoggingEvent.capture());
LoggingEvent loggingEvent = captorLoggingEvent.getValue();
//Check log level
assertThat(loggingEvent.getLevel(), is(Level.INFO));
//Check the message being logged
assertThat(loggingEvent.getRenderedMessage(),
is("String a:foo, String b:bar"));
}
}
可以ü請給出錯誤日誌 –
@AbdulManaf:我已更新錯誤消息。 –
@JohnLiva:你能告訴我們什麼是ExampleThatLogs嗎?它如何初始化其Logger? – TobiSH