Java - Logback以显示运行状态(已通过/已失败)

时间:2016-11-09 19:40:23

标签: java selenium logback slf4j

我在Selenium Webdriver项目中使用Logback,我正试图在测试结束时找到一种记录状态(测试通过或失败)的方法,所以在查看日志时你知道哪个测试失败了。

我有afterMethod我目前正在记录“ testGoogleWebsite已完成”,但想要“ testGoogleWebsite失败”或“ testGoogleWebsite已通过“。

我的测试:

@Test
 public void testGoogleWebsite() {
    openGoogleWebsite();
    searchForStackOverflow();
    clickOnStackOverflowLink();
}


@AfterMethod
public void afterMethod(Method method){
    LOG.debug(method.getName() + " has finished");
}

我的回溯文件:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <property name="DEV_HOME" value="target/Logs" />

    <appender name="FILE-AUDIT" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${DEV_HOME}/debug.log</file>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <Pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</Pattern>
        </encoder>

        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- rollover daily -->
            <fileNamePattern>${DEV_HOME}/archived/debug.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>

    </appender>

    <logger name="com.test" level="debug" additivity="false">
        <appender-ref ref="FILE-AUDIT" />
    </logger>

    <root level="debug">
        <appender-ref ref="FILE-AUDIT" />
    </root>

</configuration>

2 个答案:

答案 0 :(得分:1)

@AfterMethod
public void afterMethod(ITestResult result)
{

    String tcName = result.getName();
    if(result.getStatus() == ITestResult.SUCCESS)
    {

        //Do something here
        LOG.debug(tcName  + " has passed");
    }

    else if(result.getStatus() == ITestResult.FAILURE)
    {
         //Do something here
        LOG.debug(tcName  + " has failed");

    }

     else if(result.getStatus() == ITestResult.SKIP ){

       LOG.debug(tcName  + " has skipped");
    }
}

答案 1 :(得分:0)

因为我看过@AfterMethod,我认为你使用 TestNG

然后,您可以尝试:

@AfterMethod
public void tearDown(ITestResult result) {
   String methodName = result.getMethod().getMethodName();
   if (result.getStatus() == ITestResult.FAILURE) {
       LOG.debug(methodName + " has failed");
   } else if (result.getStatus() == ITestResult.SUCCESS) {
       LOG.debug(methodName + " has passed");
   }       
}