I am executing TestNG tests , and the logging output is set to DEBUG
, so in case of a failure I can get to inspect exactly what goes wrong.
The problem is that the output is extremely verbose, and it's bothering everyone when it runs . I would like to capture all Log4J logging events - which is easy - and only print them when the test fails. Also, I need to take into account @Before/@After
methods and also print output for them.
Assuming that I already have a List of Log4J LoggingEvent
s , how can I print those only when the Test
/After
/Before
methods fail?
Use Reporter.log(str) to log the message on the report.
@AfterMethod
public void printLOGonFailure(ITestResult result) {
if (result.getStatus() == ITestResult.FAILURE) {
String str = getLog();
Reporter.log(str);
}
}
This site has a explanation on how to do it.. I copied the code part here in case the link goes dead.
Logger.getLogger(this.getClass())
log4j.rootLogger=ERROR,TESTAPPENDER
log4j.appender.TESTAPPENDER=com.my.fantastic.MockedAppender
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class FooTest {
private Appender appenderMock;
@Before
public void setupAppender() {
appenderMock = mock(Appender.class);
Logger.getRootLogger().addAppender(appenderMock);
}
@After
public void removeAppender() {
Logger.getRootLogger().removeAppender(appenderMock);
}
@Test
public void testMethod() {
doStuffThatCausesLogging();
verify(appenderMock).doAppend((LoggingEvent) anyObject());
}
}
ArgumentCaptor arguments = ArgumentCaptor.forClass(LoggingEvent.class);
verify(appenderMock).doAppend(arguments.capture());
assertThat(arguments.getValue().getLevel(), is(Level.WARN));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With