JAVA單元測試框架-13-TestNG中的Listener監聽

鹿少年發表於2020-12-02

使用TestNG中的Listener完成監聽測試,通過實現ITestListener裡面的方法完成測試過程監聽


public class TestListenner implements ITestListener {
    @Override
    public void onTestStart(ITestResult result) {
        
    }

    @Override
    public void onTestSuccess(ITestResult result) {

    }

    @Override
    public void onTestFailure(ITestResult result) {

    }

    @Override
    public void onTestSkipped(ITestResult result) {

    }

    @Override
    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {

    }

    @Override
    public void onStart(ITestContext context) {

    }

    @Override
    public void onFinish(ITestContext context) {

    }
}

實現類:

package Listener;

import org.apache.log4j.Logger;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

public class TestListenner implements ITestListener {
    Logger logger = Logger.getLogger(TestListenner.class);
    @Override
    public void onTestStart(ITestResult result) {
        logger.info("用例啟動。" + result.toString());
    }

    @Override
    public void onTestSuccess(ITestResult result) {
        logger.info("用例執行成功," + result.toString());
    }

    @Override
    public void onTestFailure(ITestResult result) {
        logger.info("用例執行失敗,啟動截圖。");
    }

    @Override
    public void onTestSkipped(ITestResult result) {

    }

    @Override
    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {

    }

    @Override
    public void onStart(ITestContext context) {

    }

    @Override
    public void onFinish(ITestContext context) {

    }
}

執行testng.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="All Test Suite">
    <test verbose="2" preserve-order="true" name="D:/IdeaProject/interfaceRestAssured">
        <classes>
           <class name="TestNg.TestAssert">
           </class>
        </classes>
    </test>
  <!--  <listeners>
        <listener class-name="report.ExtentReport"></listener>
    </listeners>-->
  <!-- 這是reportNG的監聽類-->
  <!--  <listeners>
         <listener class-name="org.uncommons.reportng.HTMLReporter"></listener>
         <listener class-name="org.uncommons.reportng.JUnitXMLReporter"></listener>
     </listeners>-->
    <listeners>
        <listener class-name="Listener.TestListenner"></listener>
    </listeners>
</suite>

執行截圖:

 用例執行 執行成功與失敗都會列印執行資訊

相關文章