1

我是 ExtentReports 的新手。我浏览了 youtube 中的许多视频,以使用具有上述标题条件的 ExtentReports 生成报告,但没有找到我正在寻找的确切答案。

当尝试在 testng 套件中执行多个类时,它会显示 nullpointerexception 假设假设套件包含 3 个类(测试用例)。对于一流的执行进展顺利。一旦它跳到第二个类,它就会显示 NullPointerException。下面是我的代码

注意:用@BeforeTest 和@AfterTest 也试过......

public class AppInit {

    public ExtentReports reports;
    public ExtentTest testInfo;
    public ExtentHtmlReporter htmlReporter;

    @BeforeSuite
    public void reportSetup() {
        htmlReporter = new ExtentHtmlReporter(new File(System.getProperty("user.dir") + "/AutomationReports.html"));
        htmlReporter.loadXMLConfig(new File(System.getProperty("user.dir") + "/src/resource/XML/Extent-Config.xml"));
        reports = new ExtentReports();
        htmlReporter.setAppendExisting(true);
        reports.setSystemInfo("Environment", "Automation");
        reports.attachReporter(htmlReporter);
    }

    @BeforeMethod
    public void testMethodName(Method method) {
        String testName = method.getName();
        testInfo = reports.createTest(testName);
    }

    @AfterMethod
    public void capture_TestStatus(ITestResult result) {
        try {
            if (result.getStatus() == ITestResult.SUCCESS) {
                testInfo.log(Status.PASS, "Test method " + "'" + result.getName() + "'" + result.getStatus());
            } else if (result.getStatus() == ITestResult.FAILURE) {
                testInfo.log(Status.FAIL, "Test method " + "'" + result.getName() + "'" + result.getStatus());
                testInfo.log(Status.FAIL, "Test error " + result.getThrowable());
            } else if (result.getStatus() == ITestResult.SKIP) {
                testInfo.log(Status.SKIP, "Test method " + "'" + result.getName() + "'" + result.getStatus());
            }

        } catch (Exception e) {    
            e.printStackTrace();    
        }
    }

    @AfterSuite
    public void generateReport() {
        reports.flush();
    }
}

异常/错误

aaa#poolUsable 从 2018 年 3 月 30 日晚上 10:21:21 开始 main.java.com.xxx.yyy.framework.LogTestListener 日志信息:test.java.com.xxx.yyy.tests.modules.zzz.explore.Capacity。 aaa#poolUsable 已跳过测试运行:9,失败:1,错误:0,已跳过:7,已用时间:38.356 秒 <<< 失败!- 在 TestSuite 中 testMethodName(test.java.com.xxx.yyy.tests.modules.zzz.explore.Capacity.aaa) 已用时间:14.078 秒 <<< 失败!java.lang.NullPointerException:在 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 sun.reflect.NativeMethodAccessorImpl.invoke 的 main.java.com.xxx.yyy.framework.AppInit.testMethodName(AppInit.java:178) 处为 null (NativeMethodAccessorImpl.java:62) 在 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.lang。

Results :

Failed tests: 
test.java.com.xxx.yyy.tests.modules.zzz.explore.Capacity.aaa.testMethodName(test.java.com.xxx.yyy.tests.modules.zzz.explore.Capacity.aaa)
  Run 1: aaa>AppInit.testMethodName:178 » NullPointer
  Run 2: PASS


Tests run: 7, Failures: 1, Errors: 0, Skipped: 5

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 43.588 s
[INFO] Finished at: 2018-03-30T22:21:22+05:30
[INFO] Final Memory: 21M/259M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.18.1:test

项目框架上的(默认测试):有测试失败。[错误] [错误] 个别测试结果请参考 C:\bbb\Project_Workspace\Framework\target\surefire-reports。[ERROR] -> [Help 1] [ERROR] [ERROR] 要查看错误的完整堆栈跟踪,请使用 -e 开关重新运行 Maven。[错误] 使用 -X 开关重新运行 Maven 以启用完整的调试日志记录。[ERROR] [ERROR] 有关错误和可能的解决方案的更多信息,请阅读以下文章: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

在 Maven 中执行单个 TestNg 套装(具有多个类)。套房长这样

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="ReportLibrary_Inventory_Test" parallel="tests">

    <listeners>
        <listener class-name="main.java.com.xxx.yyy.framework.LogTestListener"/>
    </listeners>

    <parameter name="browser" value="firefox" />
    <parameter name="sUsername" value="aaa" />
    <parameter name="sPassword" value="bbb" />

    <test name="zzz_ReportLibrary_Inventory" enabled="true" preserve-order="true" group-by-instances="true">
        <classes>
            <class name="test.java.com.aaa.yyy.tests.modules.zzz.reportlibrary.inventory.ccc"></class>
            <class name="test.java.com.aaa.yyy.tests.modules.zzz.reportlibrary.inventory.ddd"></class>
            <class name="test.java.com.aaa.yyy.tests.modules.zzz.reportlibrary.inventory.eee"></class>
            <!-- <class name="test.java.com.aaa.yyy.tests.modules.zzz.reportlibrary.inventory.Sample"></class> -->
            <class name="test.java.com.aaa.yyy.tests.modules.zzz.reportlibrary.inventory.fff"></class>
            <!-- <class name="test.java.com.aaa.yyy.tests.modules.zzz.reportlibrary.inventory.ggg"></class> -->
        </classes>
    </test>
</suite>

在 maven(pom.xml) 中执行多个 testng 套件

<suiteXmlFiles>
    <!-- <suiteXmlFile>src/resource/TestNg_XML/zzz_ReportLibrary_Inventory.xml</suiteXmlFile> -->
    <!-- <suiteXmlFile>src/resource/TestNg_XML/zzz_ReportLibrary_Summary_TableView.xml</suiteXmlFile> -->
    <suiteXmlFile>src/resource/TestNg_XML/zzz_Explore_Attributes.xml</suiteXmlFile>
    <!-- <suiteXmlFile>src/resource/TestNg_XML/zzz_All.xml</suiteXmlFile> -->
</suiteXmlFiles>

请帮我解决这个问题。我没时间送货了

提前致谢:)

指定类代码

package main.java.com.xxx.zzz.framework;

import java.io.File;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.w3c.dom.Document;

import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;

import page.pageactions.LoginPageActions;
import page.pageactions.reportlibrarypageactions.ReportLibraryPageActions;
import test.java.com.xxx.zzz.tests.modules.centralizedManagement.Collecting;
import test.java.com.xxx.zzz.tests.modules.centralizedManagement.Modify_PollingInterval;

public class AppInit {

    public static WebDriver driver;
    public String convertStatus;
    public String className;
    public String testCase_MethodName;
    public final static int Timer_Web_Element_Show = 30;

    public static String retrievedUserEnteredbbbNamezzzUI;

    public ExtentReports reports;
    public ExtentTest testInfo;
    public ExtentHtmlReporter htmlReporter;

    // XML Parser
    public static String resBodyXMLFilesPath;
    public static File file;
    public static DocumentBuilderFactory dbFactory;
    public static DocumentBuilder dBuilder;
    public static Document doc;
    public static XPath xPath;

    @BeforeSuite
    public void reportSetup() {

        htmlReporter = new ExtentHtmlReporter(new File(System.getProperty("user.dir") + "/AutomationReports.html"));
        htmlReporter.loadXMLConfig(new File(System.getProperty("user.dir") + "/src/resource/XML/Extent-Config.xml"));
        reports = new ExtentReports();
        htmlReporter.setAppendExisting(true);
        reports.setSystemInfo("Environment", "Automation");
        reports.attachReporter(htmlReporter);

    }

    @BeforeSuite
    @Parameters({ "browser", "sUsername", "sPassword" })
    public void setup(String browser, String sUsername, String sPassword) throws Exception {

        DataProviders.getPropertyData();
        CommonMethods.deleteFilesFromDirectory("TestCaseResult_FolderPath");
        // CommonMethods.deleteFilesFromDirectory("DownloadedFiles_Path");

        // Check if parameter passed from TestNG is 'firefox'
        if (browser.equalsIgnoreCase("firefox")) {
            FirefoxProfile profile = new FirefoxProfile();
            profile.setPreference("browser.download.folderList", 2);
            profile.setPreference("browser.download.manager.showWhenStarting", false);
            profile.setPreference("browser.download.dir",
                    CommonMethods.relativePath("", "\\src\\resource\\Downloaded_Files"));
            profile.setPreference("browser.helperApps.neverAsk.openFile",
                    "application/log,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;");
            profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
                    "application/log,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;");
            profile.setPreference("browser.helperApps.alwaysAsk.force", false);
            profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
            profile.setPreference("browser.download.manager.focusWhenStarting", false);
            profile.setPreference("browser.download.manager.useWindow", false);
            profile.setPreference("browser.download.manager.showAlertOnComplete", false);
            profile.setPreference("browser.download.manager.closeWhenDone", false);

            // create firefox instance
            // System.setProperty("webdriver.firefox.marionette",
            // ".\\geckodriver.exe");
            driver = new FirefoxDriver(profile);
        }
        // Check if parameter passed as 'chrome'
        else if (browser.equalsIgnoreCase("chrome")) {
            // set path to chromedriver.exe
            System.setProperty("webdriver.chrome.driver",
                    CommonMethods.relativePath("chromedriver.exe", "\\src\\lib\\"));
            // create chrome instance
            driver = new ChromeDriver();
        } else {
            // If no browser passed throw exception
            throw new Exception("Browser is not correct");
        }

        driver.get(CommonMethods.dp_DataCollector("url"));
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

        // Logging into zzz
        LoginPageActions.username(sUsername);
        LoginPageActions.password(sPassword);
        LoginPageActions.loginButton();


          Modify_PollingInterval.modify_TopologyPolling(); System.out.println(
          "Topology polling executed successfully");
          Modify_PollingInterval.modify_PerformancePolling();
          System.out.println("Performance Polling executed successfully");

          System.out.println("Modifying level and log file size started");
          CommonMethods.ssh_ExecuteCommand("Collector_UserName",
          "Collector_Password", "Collector_IP", "Collector_Port",
          "sed -i 's/INFO/FINEST/g' /opt/APG/Collecting/Collector-Manager/yyy-aaa/conf/logging.properties && (>&2 echo 'Success') || (>&2 echo 'Fail')"
          ); CommonMethods.ssh_ExecuteCommand("Collector_UserName",
          "Collector_Password", "Collector_IP", "Collector_Port",
          "sed -i 's/1048576/1000048576/g' /opt/APG/Collecting/Collector-Manager/yyy-aaa/conf/logging.properties  && (>&2 echo 'Success') || (>&2 echo 'Fail')"
          ); System.out.println("Modified level and log file size");

          System.out.println("Re-Starting collector manager started");
          CommonMethods.ssh_ExecuteCommand("Collector_UserName",
          "Collector_Password", "Collector_IP", "Collector_Port",
          "apg-collector-manager-yyy-aaa restart  && (>&2 echo 'Success') || (>&2 echo 'Fail')"
          ); CommonMethods.pauseTime(8); System.out.println(
          "Restarted collector manager");

          System.out.println("Verifying one successful poll");
          CommonMethods.polling_Check("Collector_UserName",
          "Collector_Password", "Collector_IP", "Collector_Port");
          System.out.println("One successful polling is done");

          System.out.println("Downloading the log file");
          CommonMethods.ssh_DownloadLogFile("Collector_UserName",
          "Collector_Password", "Collector_IP", "Collector_Port");
          System.out.println("Downloaded log file");

          CommonMethods.get_ResponceBodyfromLog(CommonMethods.
          retrieveLatestFileName_Downloaded().toString(),
          "CreateNew_LogFile_aaa", "StartPoint_aaa", "EndPoint_aaa");

          Collecting.dataBase_ImportPropertiesTask(); System.out.println(
          "Property store executed successfully");


        // Holding XML data in a doc for parsing it
        resBodyXMLFilesPath = System.getProperty("user.dir") + CommonMethods.dp_DataCollector("CreateNew_LogFile_aaa");
        file = new File(resBodyXMLFilesPath + ".xml");
        dbFactory = DocumentBuilderFactory.newInstance();
        dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.parse(file);
        doc.getDocumentElement().normalize();
        xPath = XPathFactory.newInstance().newXPath();

        retrievedUserEnteredbbbNamezzzUI = ReportLibraryPageActions.retrieveUserEnteredbbbName();
    }

    @BeforeMethod
    public void testMethodName(Method method) {

        String testName = method.getName();
        testInfo = reports.createTest(testName);

    }

    @AfterMethod
    public void capture_TestStatus(ITestResult result) {

        try {


            if (result.getStatus() == ITestResult.SUCCESS) {
                testInfo.log(Status.PASS, "Test method " + "'" + result.getName() + "'" + result.getStatus());
            } else if (result.getStatus() == ITestResult.FAILURE) {
                testInfo.log(Status.FAIL, "Test method " + "'" + result.getName() + "'" + result.getStatus());
                testInfo.log(Status.FAIL, "Test error " + result.getThrowable());
            } else if (result.getStatus() == ITestResult.SKIP) {
                testInfo.log(Status.SKIP, "Test method " + "'" + result.getName() + "'" + result.getStatus());
            }



        } catch (Exception e) {

            e.printStackTrace();

        }



    }

    @AfterSuite
    public void generateReport() {

        reports.flush();

    }

    @AfterSuite
    public void tearDown() {

        CommonMethods.pauseTime(5);

        // reports.flush();

        driver.quit();

    }

}

按照建议修改代码

public class AppInit implements ISuiteListener, IInvokedMethodListener {
    public void onStart(ISuite suite){

            //Extent Reports
            htmlReporter = new ExtentHtmlReporter(new File(System.getProperty("user.dir") + "/AutomationReports.html"));
            htmlReporter.loadXMLConfig(new File(System.getProperty("user.dir") + "/src/resource/XML/Extent-Config.xml"));
            reports = new ExtentReports();
            htmlReporter.setAppendExisting(true);
            reports.setSystemInfo("Environment", "Automation");
            reports.attachReporter(htmlReporter);

            DataProviders.getPropertyData();
            CommonMethods.deleteFilesFromDirectory("TestCaseResult_FolderPath");
            // CommonMethods.deleteFilesFromDirectory("DownloadedFiles_Path");

            // Check if parameter passed from TestNG is 'firefox'
            String getBrowserInput = suite.getParameter("browser");
            if (getBrowserInput.equalsIgnoreCase("firefox")) {
                FirefoxProfile profile = new FirefoxProfile();
                profile.setPreference("browser.download.folderList", 2);
                profile.setPreference("browser.download.manager.showWhenStarting", false);
                profile.setPreference("browser.download.dir",
                        CommonMethods.relativePath("", "\\src\\resource\\Downloaded_Files"));
                profile.setPreference("browser.helperApps.neverAsk.openFile",
                        "application/log,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;");
                profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
                        "application/log,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;");
                profile.setPreference("browser.helperApps.alwaysAsk.force", false);
                profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
                profile.setPreference("browser.download.manager.focusWhenStarting", false);
                profile.setPreference("browser.download.manager.useWindow", false);
                profile.setPreference("browser.download.manager.showAlertOnComplete", false);
                profile.setPreference("browser.download.manager.closeWhenDone", false);

                // create firefox instance
                // System.setProperty("webdriver.firefox.marionette",
                // ".\\geckodriver.exe");
                driver = new FirefoxDriver(profile);
            }
            // Check if parameter passed as 'chrome'
            else if (getBrowserInput.equalsIgnoreCase("chrome")) {
                // set path to chromedriver.exe
                System.setProperty("webdriver.chrome.driver",
                        CommonMethods.relativePath("chromedriver.exe", "\\src\\lib\\"));
                // create chrome instance
                driver = new ChromeDriver();
            } else {
                // If no browser passed throw exception
                try {
                    throw new Exception("Browser is not correct");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            driver.get(CommonMethods.dp_DataCollector("url"));
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

            // Logging into aaa
            String getUserName = suite.getParameter("sUsername");
            String getPassword = suite.getParameter("sPassword");
            LoginPageActions.username(getUserName);
            LoginPageActions.password(getPassword);
            LoginPageActions.loginButton();

            resBodyXMLFilesPath = System.getProperty("user.dir") + CommonMethods.dp_DataCollector("CreateNew_LogFile_bbb");
            file = new File(resBodyXMLFilesPath + ".xml");
            dbFactory = DocumentBuilderFactory.newInstance();
            try {
                dBuilder = dbFactory.newDocumentBuilder();
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                doc = dBuilder.parse(file);
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            doc.getDocumentElement().normalize();
            xPath = XPathFactory.newInstance().newXPath();

            retrievedUserEnteredcccNameaaaUI = ReportLibraryPageActions.retrieveUserEnteredcccName();

        }

        public void onFinish(ISuite suite) {

            CommonMethods.pauseTime(5);

             reports.flush();

            driver.quit();

        }

        public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {

            String testName = method.getTestMethod().getMethodName();
            testInfo = reports.createTest(testName);

        }

        public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
            if (testResult.getStatus() == ITestResult.SUCCESS) {
                testInfo.log(Status.PASS, "Test method " + "'" + testResult.getName() + "'" + testResult.getStatus());
            } else if (testResult.getStatus() == ITestResult.FAILURE) {
                testInfo.log(Status.FAIL, "Test method " + "'" + testResult.getName() + "'" + testResult.getStatus());
                testInfo.log(Status.FAIL, "Test error " + testResult.getThrowable());
            } else if (testResult.getStatus() == ITestResult.SKIP) {
                testInfo.log(Status.SKIP, "Test method " + "'" + testResult.getName() + "'" + testResult.getStatus());
            }

        }
}

移除监听器后的输出

[INFO] 正在扫描项目... [INFO]
[信息] --------------------------------------------- ------------- [INFO] 构建aaa 3.7-SNAPSHOT [INFO] -------------- -------------------------------------------------- -------- [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @aaa --- [INFO] 使用 'UTF-8' 编码复制过滤的资源. [INFO] 复制 14 个资源 [INFO] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @aaa --- [INFO] 没有可编译的 - 所有类都是最新的 [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ aaa --- [INFO] 使用 'UTF-8' 编码复制过滤的资源。[INFO] 跳过不存在的资源目录 C:\zzz\bbb\aaa\src\test\resources [INFO] [INFO] --- maven-compiler-plugin:3.1: testCompile (default-testCompile) @aaa --- [INFO] Changes detected - 重新编译模块![INFO] 编译 13 个源文件到 C:\zzz\bbb\aaa\target\test-classes [INFO] [INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @aaa - -- [INFO] Surefire 报告目录:C:\zzz\bbb\aaa\target\surefire-reports

SuiteRunner$SuiteWorker.run(SuiteRunner.java:368) at org.testng.internal.thread.ThreadUtil$2.call(ThreadUtil.java:64) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) 在 java.lang.Thread.run(Thread.java:748)测试运行:2,失败:1,错误:0,跳过:0,经过的时间:4.799 秒 <<< 失败!- 在 TestSuite 磁盘名称(test.java.com.xxx.yyy.tests.modules.ccc_ddd.reportlibrary.inventory.disks)中经过的时间:2.071 秒 <<< 失败!java.lang.NullPointerException:在 org.openqa.selenium.support.ui.FluentWait.(FluentWait.java:94) 的 org.openqa.selenium.support.ui.FluentWait.(FluentWait.java:94) 的 com.google.common.base.Preconditions.checkNotNull(Preconditions.java:210) 处为空。

结果 :

测试失败:disks.diskName:21 » NullPointer

测试运行:2,失败:1,错误:0,跳过:0

[信息] --------------------------------------------- ------------------------- [信息] 构建失败 [信息] ----------------- -------------------------------------------------- ----- [INFO] 总时间:9.667 s [INFO] 完成时间:2018-04-03T18:47:16+05:30 [INFO] 最终内存:21M/259M [INFO] ------ -------------------------------------------------- ---------------- [错误] 无法在项目 aaa 上执行目标 org.apache.maven.plugins:maven-surefire-plugin:2.18.1:test (default-test) : 有测试失败。[ERROR] [ERROR] 个别测试结果请参考 C:\zzz\bbb\aaa\target\surefire-reports。[ERROR] -> [Help 1] [ERROR] [ERROR] 要查看错误的完整堆栈跟踪,请使用 -e 开关重新运行 Maven。[错误] 使用 -X 开关重新运行 Maven 以启用完整的调试日志记录。 http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

4

2 回答 2

1

问题在于您使用@BeforeSuite@BeforeTest注释的方式。

@BeforeSuite/注释的方法将由TestNG 每个标签@AfterSuite仅执行一次。<suite>因此,假设您<suite>包含两个或多个<test>标签,即使这样 TestNG 也只会执行一次。

@BeforeSuite/注释的方法将由TestNG 每个标签@AfterSuite仅执行一次。<test>因此,假设您<test>包含两个或多个类,即使这样 TestNG 也只会执行一次。

看起来你所有的测试类基本上都在扩展类AppInit

所以只有在你的第一堂课<test>才会被执行。从第二个类开始,它将被跳过,即使第二个类也具有该方法作为继承的一部分。@BeforeSuite@BeforeTest

您将需要采用不同的机制来使用ExtentReports. 我建议您使用 TestNG 侦听器,在其中构建一个侦听器,该侦听器实现org.testng.ISuiteListener您的@BeforeSuite/@AfterSuite逻辑并将其移动到此侦听器中,并且在同一实现中,让您的类也实现org.testng.IInvokedMethodListener并将您的@BeforeMethod/@AfterMethod逻辑移动到此实现中。

最后,您将此侦听器连接到您的套件中。

于 2018-03-31T08:29:11.370 回答
0

终于能够解决了。这是一个小错误,即我没有使用静态变量,而是使用普通变量。

@BeforeSuite
// Invoking ExtentReports functionality
public void reportSetup() {

    htmlReporter = new ExtentHtmlReporter(new File(System.getProperty("user.dir") + "/AutomationReports.html"));
    htmlReporter.loadXMLConfig(new File(System.getProperty("user.dir") + "/src/resource/XML/Extent-Config.xml"));
    reports = new ExtentReports();
    reports.setSystemInfo("Environment", "Automation");
    reports.attachReporter(htmlReporter);

}

@BeforeMethod
public void testMethodName(Method method) {

    String testName = method.getName();
    testInfo = reports.createTest(testName);

}

@AfterMethod
public void capture_TestStatus(ITestResult result) {

    try {

        if (result.getStatus() == ITestResult.SUCCESS) {
            testInfo.log(Status.PASS, "Test method " + "'" + result.getName() + "'" + result.getStatus());
        } else if (result.getStatus() == ITestResult.FAILURE) {
            testInfo.log(Status.FAIL, "Test method " + "'" + result.getName() + "'" + result.getStatus());
            testInfo.log(Status.FAIL, "Test error " + result.getThrowable());
        } else if (result.getStatus() == ITestResult.SKIP) {
            testInfo.log(Status.SKIP, "Test method " + "'" + result.getName() + "'" + result.getStatus());
        }

    } catch (Exception e) {

        e.printStackTrace();

    }

}

@AfterSuite
public void tearDown() {

    CommonMethods.pauseTime(5);
    reports.flush();
    driver.quit();

}
于 2018-04-09T07:05:32.517 回答