简体   繁体   English

使用Log4j时,如何在测试失败时写入日志文件

[英]How to write to log file when test fail, with Log4j

I want to achieve writing to log file with Log4j . 我想用Log4j实现写入日志文件。

I have found one easy solution - surround test body with try - catch : 我找到了一个简单的解决方案 - 环绕测试体,带有try - catch

@Test(groups = "GMAIL_PAGE")
public void testAllMailLink() {
    try {
        List<WebElement> allMessages = page.takeAllMessage();
        page.clickInboxLink();
        List<WebElement> inboxMessages = page.takeInboxMessage();
        page.clickDraftLink();
        List<WebElement> draftMessages = page.takeDraftMessage();

        Assert.assertTrue(allMessages.containsAll(inboxMessages),
                "All messages doesn't contains all inbox messages");
        Assert.assertTrue(allMessages.containsAll(draftMessages),
                "All messages doesn't contains all draft messages");
        log.info("test is passed");
    } catch (Exception e) {
        log.error(e);
    }
}

But it has some drawbacks - this test is always passed, even if it fails. 但它有一些缺点 - 这个测试总是通过,即使它失败了。

It is ok if I work on my machine and able to see console. 如果我在我的机器上工作并且能够看到控制台,那就没问题。 But what to do when this test is pushed to Continuous Integration server? 但是当将此测试推送到Continuous Integration服务器时该怎么办?

Does exist any other way to write info into log file, when test fail? 当测试失败时,是否存在将信息写入日志文件的任何其他方式?

Add Assert.fail() below your log.error(e) : log.error(e)下面添加Assert.fail() log.error(e)

catch (Exception e) {
    log.error(e);
    Assert.fail();
}

By the way, you're calling Logger#error(Object) , which uses e.toString() . 顺便说一句,你正在调用Logger#error(Object) ,它使用e.toString() In this case, it is better to use a descriptive message and then pass the exception to get the respective stacktrace: 在这种情况下,最好使用描述性消息,然后传递异常以获取相应的堆栈跟踪:

catch (Exception e) {
    log.error("Some descriptive message should go here.", e);
    Assert.fail("Some descriptive message should go here as well.");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM