当前位置: 首页 > 知识库问答 >
问题:

与范围报告并行执行测试的问题

太叔富
2023-03-14

我试图用ExtentReport和TestNG执行我的基本项目测试,但当我执行2个类时,ExtentTestManager中的“categoryName”。java由第二个测试填充,而第一个测试没有运行。我尝试实现一个LocalThread来完成这项任务,但我无法实现。。。

扩展测试管理器.java

    package com.daimler.qa.util.ExtentReports;

import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import org.testng.Reporter;

import java.util.HashMap;
import java.util.Map;

public class ExtentTestManager {

    static Map<Integer, ExtentTest> extentTestMap = new HashMap<>();
    public static ExtentReports extent = ExtentManager.getInstance();
    private static final ThreadLocal<String> categoryName = new ThreadLocal<>();

    public static synchronized ExtentTest getTest(){
        return extentTestMap.get((int) Thread.currentThread().getId());
    }

    public static synchronized void endTest(){
        extent.flush();
    }

    public synchronized static void createTest(String testName, String description){
        extentTestMap.put((int) Thread.currentThread().getId(), extent.createTest(testName, description));
        System.out.println("-------------------"+Thread.currentThread().getId()+"------------------------------------");
    }

    public static ThreadLocal<String> getCategoryName(){
        System.out.println("--------------------------"+categoryName+"---------------------------");
        return categoryName;
    }

    public static void setCategoryName(String categoryName){
        getCategoryName().set(categoryName);
    }

    public synchronized static void reporterLog(String log){
        if(ExtentTestManager.getTest() != null){
            ExtentTestManager.getTest().log(Status.INFO, log);
            Reporter.log(log);
        }
    }
}

范围曼安格.java

package com.daimler.qa.util.ExtentReports;

import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
import com.aventstack.extentreports.reporter.configuration.Theme;
import com.daimler.qa.base.TestBase;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

public class ExtentManager extends TestBase {

    public static Properties prop;


    private static String reportBaseDirectory;
    private static ExtentReports extent;
    private static String df = new SimpleDateFormat("yyyy_MM_dd/hh_mm").format(new Date());
    public static final String REPORT_FILE_PATH = System.getProperty("user.dir") + "/Reports/"+df+"/";
    private static String onlyDate = new SimpleDateFormat("yyyy_MM_dd").format(new Date());


    public static ExtentReports getInstance() {
        if (extent == null) {
            createInstance();
        }
        return extent;
    }


    public static void createInstance() {
        try {
            prop = new Properties();
            FileInputStream ip = new FileInputStream(System.getProperty("user.dir") + "/src/main/java/com/daimler/qa/config/config.properties");
            prop.load(ip);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        ExtentManager.initDirectories();
        setReportBaseDirectory(REPORT_FILE_PATH);
        ExtentSparkReporter htmlReporter = new ExtentSparkReporter(REPORT_FILE_PATH + "Test_automation_report_"+onlyDate+".html");
        htmlReporter.config().setTheme(Theme.DARK);
        htmlReporter.config().setEncoding("utf-8");
        htmlReporter.config().setReportName("Automation test results");
        htmlReporter.config().setJs("$('.brand-logo').text('FarEye');");
        htmlReporter.config().setTimeStampFormat("EEEE, MMMM, dd, yyyy, hh:mm a '('zzz')'");
        extent = new ExtentReports();
        extent.attachReporter(htmlReporter);
        extent.setSystemInfo("User", prop.getProperty("username"));
        extent.setSystemInfo("ENVIRONMENT", prop.getProperty("environment"));
        extent.setSystemInfo("BROWSER", prop.getProperty("browser"));
    }

    public synchronized static String getReportBaseDirectory() {
        return reportBaseDirectory;
    }

    public synchronized static void setReportBaseDirectory(String reportBaseDirectory) {
        ExtentManager.reportBaseDirectory = reportBaseDirectory;
    }

    public static void initDirectories() {
        try {
            createFolder(REPORT_FILE_PATH);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void createFolder(String folderPath) {
        File file = new File(folderPath);
        if (!file.exists()) file.mkdirs();
    }

    public static synchronized String takeScreenshot(String methodName) throws IOException {

        //create object variable of TakeScreenshot class
        TakesScreenshot ts = (TakesScreenshot)driver;

        //create File object variable which holds the screen shot reference
        File source = ts.getScreenshotAs(OutputType.FILE);

        //store the screen shot path in path variable. Here we are storing the screenshots under screenshots folder
        String path = System.getProperty("user.dir")+"/Reports/"+df+"/Screenshots/"+methodName+".png";

        //create another File object variable which points(refer) to the above stored path variable
        File destination = new File(path);

        //use FileUtils class method to save the screen shot at desired path
        FileUtils.copyFile(source, destination);

        return path;
    }
}

测试侦听器.java

package com.daimler.listener;

import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.daimler.qa.base.TestBase;
import com.daimler.qa.util.ExtentReports.ExtentManager;
import com.daimler.qa.util.ExtentReports.ExtentTestManager;
import org.openqa.selenium.*;
import org.openqa.selenium.support.events.WebDriverEventListener;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;



import java.io.IOException;


public class TestListener extends TestBase implements ITestListener, WebDriverEventListener {


    //EXTENT REPORT
    private static long endTime;

    private static void setStartTime(long startTime){

    }
    private static void setEndTime(long endTime){
        TestListener.endTime = endTime;
    }

    @Override
    public synchronized void onTestStart(ITestResult iTestResult) {
        System.out.println("--------------Executing :- "+getSimpleClassName(iTestResult)+"--------------");
        ExtentTestManager.createTest(iTestResult.getName(),iTestResult.getMethod().getDescription());
        ExtentTestManager.setCategoryName(getSimpleClassName(iTestResult));
        System.out.println("--------------------"+getSimpleClassName(iTestResult)+"---------------------");
    }

    @Override
    public synchronized void onTestSuccess(ITestResult iTestResult) {
        ExtentTestManager.getTest().assignCategory(getSimpleClassName(iTestResult));
        addExtentLabelToTest(iTestResult);
        ExtentTestManager.endTest();
    }

    @Override
    public synchronized void onTestFailure(ITestResult iTestResult) {
        ExtentTestManager.getTest().assignCategory(getSimpleClassName(iTestResult));

        /*try {
            ExtentTestManager.getTest().assignCategory(getSimpleMethodName(iTestResult)).addScreenCaptureFromPath(ExtentManager.takeScreenshot(iTestResult.getName()));
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }*/

        addExtentLabelToTest(iTestResult);
        ExtentTestManager.endTest();
    }

    @Override
    public synchronized void onTestSkipped(ITestResult iTestResult) {
        ExtentTestManager.getTest().log(Status.SKIP, iTestResult.getName()+" Test is Skipped"+iTestResult.getThrowable());
    }

    @Override
    public synchronized void onTestFailedButWithinSuccessPercentage(ITestResult iTestResult) {
    }

    @Override
    public void onTestFailedWithTimeout(ITestResult result) {

    }

    @Override
    public synchronized void onStart(ITestContext iTestContext) {

    }

    @Override
    public synchronized void onFinish(ITestContext iTestContext) {
        setStartTime(iTestContext.getStartDate().getTime());
        setEndTime(iTestContext.getEndDate().getTime());
    }

    private synchronized String getSimpleClassName(ITestResult iTestResult){
        return iTestResult.getTestClass().getRealClass().getSimpleName();
    }

    private synchronized String getSimpleMethodName(ITestResult iTestResult){
        return iTestResult.getName();
    }


    private synchronized void addExtentLabelToTest(ITestResult iTestResult){
        if(iTestResult.getStatus() == ITestResult.SUCCESS){
            ExtentTestManager.getTest().pass(MarkupHelper.createLabel("Test Passed", ExtentColor.GREEN));
        }
        else if(iTestResult.getStatus()==ITestResult.FAILURE){
            ExtentTestManager.getTest().fail(MarkupHelper.createLabel("Test Failed "+iTestResult.getName()+" in source: "+iTestResult.getInstanceName(), ExtentColor.RED));
        }
        else{
            ExtentTestManager.getTest().skip(MarkupHelper.createLabel("Test Failed "+iTestResult.getName()+" in source: "+iTestResult.getInstanceName(), ExtentColor.ORANGE));
        }
    }


    //GUIDE NAVIGATION - WEB EVENTS

    public synchronized void beforeNavigateTo(String url, WebDriver driver) {
        System.out.println("Before navigating to: '" +url+ "'");
        //ExtentTestManager.reporterLog("Before navigating to: '"+url+"'");
    }

    public void afterNavigateTo(String url, WebDriver driver) {
        System.out.println("Navigated to:'" + url + "'");
        //ExtentTestManager.reporterLog("Navigated t o:'" + url + "'");
    }

    public void beforeChangeValueOf(WebElement element, WebDriver driver) {
        System.out.println("Value of the:" + element.toString() + " before any changes made");
    }

    public void afterChangeValueOf(WebElement element, WebDriver driver) {
        System.out.println("Element value changed to: " + element.toString());
    }

    public void beforeClickOn(WebElement element, WebDriver driver) {
        System.out.println("Trying to click on: " + element.toString());
        //ExtentTestManager.reporterLog("Trying to click on: "+element.toString());
    }

    public void afterClickOn(WebElement element, WebDriver driver) {
        System.out.println("Clicked on: " + element.toString());
        //ExtentTestManager.reporterLog("Clicked on: " + element.toString());
    }

    public void beforeNavigateBack(WebDriver driver) {
        System.out.println("Navigating back to previous page");
    }

    public void afterNavigateBack(WebDriver driver) {
        System.out.println("Navigated back to previous page");
    }

    public void beforeNavigateForward(WebDriver driver) {
        System.out.println("Navigating forward to next page");
    }

    public void afterNavigateForward(WebDriver driver) {
        System.out.println("Navigated forward to next page");
    }

    public void onException(Throwable error, WebDriver driver) {
        System.out.println("Exception occured: " + error);
        /*try {
            TestUtil.takeScreenshotAtEndOfTest();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
    }

    public void beforeFindBy(By by, WebElement element, WebDriver driver) {
        System.out.println("Trying to find Element By : " + by.toString());
        //ExtentTestManager.reporterLog("Trying to find Element By : " + by.toString());
    }

    public void afterFindBy(By by, WebElement element, WebDriver driver) {
        System.out.println("Found Element By : " + by.toString());
        ExtentTestManager.reporterLog("Found Element By : " + by.toString());
    }

    /*
     * non overridden methods of WebListener class
     */
    public void beforeScript(String script, WebDriver driver) {
    }

    public void afterScript(String script, WebDriver driver) {
    }

    public void beforeAlertAccept(WebDriver driver) {
        // TODO Auto-generated method stub

    }

    public void afterAlertAccept(WebDriver driver) {
        // TODO Auto-generated method stub

    }

    public void afterAlertDismiss(WebDriver driver) {
        // TODO Auto-generated method stub

    }

    public void beforeAlertDismiss(WebDriver driver) {
        // TODO Auto-generated method stub

    }

    public void beforeNavigateRefresh(WebDriver driver) {
        // TODO Auto-generated method stub

    }

    public void afterNavigateRefresh(WebDriver driver) {
        // TODO Auto-generated method stub

    }

    public void beforeChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend) {
        // TODO Auto-generated method stub

    }

    public void afterChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend) {
        // TODO Auto-generated method stub

    }

    public <X> void afterGetScreenshotAs(OutputType<X> arg0, X arg1) {
        // TODO Auto-generated method stub

    }

    public void afterGetText(WebElement arg0, WebDriver arg1, String arg2) {
        // TODO Auto-generated method stub

    }

    public void afterSwitchToWindow(String arg0, WebDriver arg1) {
        // TODO Auto-generated method stub

    }

    public <X> void beforeGetScreenshotAs(OutputType<X> arg0) {
        // TODO Auto-generated method stub

    }

    public void beforeGetText(WebElement arg0, WebDriver arg1) {
        // TODO Auto-generated method stub

    }

    public void beforeSwitchToWindow(String arg0, WebDriver arg1) {
        // TODO Auto-generated method stub

    }


}

SearchInGoogleTest.java

package com.daimler.qa.testcases;

import com.daimler.qa.base.TestBase;
import com.daimler.qa.pages.exampleHomePage;
import com.daimler.listener.TestListener;
import org.testng.annotations.*;

@Listeners({TestListener.class})

public class searchInGoogleTest extends TestBase{

    exampleHomePage homePage;

    @BeforeMethod
    public void setUp(){
        initialization();
        homePage = new exampleHomePage();
    }

    @Test(priority=0, description="Test de ejemplo búsqueda en google 1 ")
    public void searchGoogle(){
        homePage.googleSearch(prop.getProperty("textSearch"));

    }

    @AfterMethod
    public void tearDown(){
        driver.quit();
    }

}

TestBase.java

package com.daimler.qa.base;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import com.daimler.listener.TestListener;
//import com.daimler.qa.util.WebEventListener;
import com.daimler.listener.WebEventListener;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;

import com.daimler.qa.util.TestUtil;
import org.openqa.selenium.support.events.WebDriverEventListener;

public class TestBase {
    
    public static WebDriver driver;
    public static Properties prop;
    public static EventFiringWebDriver e_driver;
    public static TestListener eventListener;

    public WebDriver getDriver(){
        return driver;
    }
    public TestBase(){
        try {
            prop = new Properties();
            FileInputStream ip = new FileInputStream(System.getProperty("user.dir")+ "/src/main/java/com/daimler/qa/config/config.properties");
            prop.load(ip);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    
    public static void initialization(){
        String browserName = prop.getProperty("browser");

        if(browserName.equals("chrome")){
            System.setProperty("webdriver.chrome.driver", "src/main/resources/drivers/chromedriver/chromedriver.exe");
            driver = new ChromeDriver(); 
        }
        /*else if(browserName.equals("FF")){
            System.setProperty("webdriver.gecko.driver", "/Users/naveenkhunteta/Documents/SeleniumServer/geckodriver"); 
            driver = new FirefoxDriver(); 
        }*/

        /*ChromeOptions options = new ChromeOptions();
        String runInTheBackground = prop.getProperty("background");

        if(runInTheBackground.equals("yes")){
            options.addArguments("headless");
            options.addArguments("no-sandbox");
            options.addArguments("disable-dev-shm-usage");
            options.addArguments("window-size=1400,900");
        }
        else {
            options.setExperimentalOption("useAutomationExtension",false);
        }*/

        e_driver = new EventFiringWebDriver(driver);
        // Now create object of EventListerHandler to register it with EventFiringWebDriver
        eventListener = new TestListener();
        e_driver.register(eventListener);
        driver = e_driver;

        driver.manage().window().maximize();
        driver.manage().deleteAllCookies();
        driver.manage().timeouts().pageLoadTimeout(TestUtil.PAGE_LOAD_TIMEOUT, TimeUnit.SECONDS);
        driver.manage().timeouts().implicitlyWait(TestUtil.IMPLICIT_WAIT, TimeUnit.SECONDS);
        
        driver.navigate().to(prop.getProperty("url"));
        
    }


}

testng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="QA BASE AUTOMATION FOR DAIMLER (ibermatica)" verbose="1" thread-count="2" parallel="classes">

    <listeners>
        <listener class-name="com.daimler.listener.TestListener"/>
    </listeners>

    <test name="QA BASE TEST FOR DAIMLER">
        <classes>
            <class name="com.daimler.qa.testcases.searchInGoogleTest"/>
            <class name="com.daimler.qa.testcases.searchInGoogleTest2"/>
        </classes>
    </test>
</suite>

共有2个答案

顾单弓
2023-03-14

始终使用局部变量,请将初始化和终止包装在每个测试中。

在并行运行中,

  1. 每个测试都应该是唯一的,而不是依赖的
  2. 无全局变量
缪兴腾
2023-03-14

我发现了问题,我正在生成一个唯一的“WebDriver驱动程序”,当测试完成时,关闭所有测试,因为它们共享驱动程序。我将驱动程序创建为ThreadLocal并修复它!

 类似资料:
  • 我正在将并行执行引入我的testNG套件中。当我将“parallel”设置为“tests”时,两个浏览器打开,两个测试的第一个类同时开始--这是我所期望的。当我将其设置为“classes”时,我希望第一个测试中的两个类同时开始,但是只有一个浏览器打开,第一个类中的第一个方法执行,然后用第二个类中的第一个方法打开一个新的浏览器,依此类推。谁能告诉我我做错了什么? 下面是我的xml文件:

  • 下午好!我使用以下堆栈进行实现自动化测试:Java8,Maven,Jenkins用于测试的自动化执行。有时(不是每次,大约占所有执行的3-5%)我会在并行执行过程中遇到测试问题。并行执行由Jenkins和Jenkins文件提供。jenkins文件的示例结构: null 我很绝望,不知道还能做什么。也许您在jenkins中的并行执行过程中也遇到过同样的问题(单个测试执行总是成功完成)。谢谢你,祝你有

  • 我正在从事一个基于Selenium/testng/java/gradle的项目,该项目采用了针对webdriver和extenttest对象的ThreadLocal方法。每当我的测试用例失败时,我都会使用RetryListener再次运行失败的测试用例1次。若它是第二次通过,我的结果仍然在扩展报告中显示为“失败”(注意,所有迭代都记录在html报告中的单个测试节点中)。stackoverflow对

  • 我有一个有多个方法的TestNG测试。范围报告在主类中有效,但当我尝试为其他方法编写日志时,我得到了空指针异常。所有教程都指向在主方法中编写日志,但没有指向其他方法。我已经努力寻找解决方案一个星期了。有人能帮我吗?谢谢 我的代码是这样的 以下内容写在主测试中 我的完整代码在这里

  • 有4个类包含测试< code>TestClass1、TestClasss2、TestClass3、TestClass4。您需要创建2个测试套件,每个套件将包含2个类,并使用< code>Maven surefire插件并行运行它们。 我创建了两个包含以下内容的xml文件: 和 也添加到: 接下来,我用命令< code>mvn clean test运行项目,项目将要运行,但是测试没有开始。我哪里错了

  • 我已经构建了一个使用Selenium Grid和TestNG的小型测试框架,我想让它支持使用扩展报告3的并行执行报告,并根据将要运行的测试套件的名称创建一个本地动态命名文件。最终的想法是运行一个包含多个类的测试套件,每个类只包含一个测试,由@Test注释定义。 这些测试是UI测试,整个测试套件可能需要大约2个小时才能完成。当TestSuite完成时,将生成一个ExantReport html报告,