开发者

Capturing Log4j output when executing TestNG tests

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 pri开发者_开发问答nt 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 LoggingEvents , 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));


Implement and register a org.testng.ITestListener and react on the callback methods.


Put JMockit in dependencies. With it logging testing is very easy.

Put in test class:

     @Cascading
final static Logger logging = Logger.getLogger(<some your>.class);

Put in test:

    testedFunction(a, b, c);
    new Verifications() {{
        logging.error("The message that should be output");
        logging.info("Another message");
    }};


You can use like the below code:

@AfterMethod
public void printLOGonFailure(ITestResult result) {
    if (result.getStatus() == ITestResult.FAILURE) {
        final Logger logger = Logger.getLogger(Create_Case_from_an_Account.class);
        PropertyConfigurator.configure("C:\\Users\\svcSelenium\\eclipse-workspace\\SeleniumWork\\classes\\log4j.properties");       
        logger.error("Opps!!Test Failed due to:"+result.getThrowable());
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜