测试失败时无法从testnglistner ontest失败方法中截取屏幕截图



请在下面找到testNGlistner的完整代码。好心检查。Package Pom;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.MediaEntityBuilder;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.ChartLocation;
import com.aventstack.extentreports.reporter.configuration.Theme;
import generic.BaseTest;
public class testNgListners extends BaseTest implements ITestListener {
    ExtentHtmlReporter htmlReporter;
    ExtentReports extent;
    ExtentTest logger;
    @Override
    public void onTestStart(ITestResult result) {

    }
    @Override
    public void onTestSuccess(ITestResult result) {
        logger = extent.createTest(result.getName());
        logger.log(Status.PASS, MarkupHelper.createLabel(result.getName(), ExtentColor.GREEN));
    }
    @Override
    public void onTestFailure(ITestResult result) {
        System.out.println("hii");
        logger = extent.createTest(result.getName());
        logger.log(Status.FAIL, MarkupHelper.createLabel(result.getName(), ExtentColor.RED));
        if (result.getStatus() == ITestResult.FAILURE) {
            TakesScreenshot take = (TakesScreenshot) driver;
            File srcFile = take.getScreenshotAs(OutputType.FILE);
            File destFile = new File("./test-output/Sceenshots/" + result.getName() + ".png");
            try {
                FileUtils.copyFile(srcFile, destFile);
                System.out.println("Screenshot is been taken for failed test case: " + result.getName());
                logger.fail("Screenshot below" + logger.addScreenCaptureFromPath("./test-output/Sceenshots/" + result.getName() + ".png"));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
    @Override
    public void onTestSkipped(ITestResult result) {
        //logger=extent.createTest(result.getName());
        logger.log(Status.SKIP, MarkupHelper.createLabel(result.getName(), ExtentColor.ORANGE));
    }
    @Override
    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {}
    @Override
    public void onStart(ITestContext context) {
        htmlReporter = new ExtentHtmlReporter("./test-output/extent.html");
        extent = new ExtentReports();
        extent.attachReporter(htmlReporter);
        extent.setSystemInfo("Host name", "localhost");
        extent.setSystemInfo("Environment", "QA");
        extent.setSystemInfo("user", "Arun K M");
        htmlReporter.config().setDocumentTitle("Hybrid Automation Report");
        htmlReporter.config().setReportName("Functional Testing");
        htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
        htmlReporter.config().setTheme(Theme.STANDARD);
    }
    @Override
    public void onFinish(ITestContext context) {
        extent.flush();
    }
}

在拍摄屏幕截图时会引发无效指针异常。请帮助我解决这个问题。PFB错误详细信息:

java.lang.nullpointerexception at pom.testnglistners.ontestfailure(testnglistners.java:53(at org.testng.internal.testlistenerhelper.runtestlisteners(testListenerHelper.java:67( atorg.testng.internal.invoker.runtestlisteners(Invoker.java:1389( 在org.testng.internal.invoker.invoketestmethods(Invoker.java:1042( 在 org.testng.internal.testmethodworker.invoketestmethods(testmethodworker.java:125( 在 org.testng.internal.testmethodworker.run(testmethodworker.java:109( atorg.testng.testrunner.privaterun(testrunner.java:648(at org.testng.testrunner.run(testrunner.java:505(at org.testng.suiterunner.runtest(suiterunner.java:455(at org.testng.suiterunner.runsequily(suiterunner.java:450(at org.testng.suiterunner.privaterun(suiterunner.java:415(at org.testng.suiterunner.run(suiterunner.java:364(at org.testng.suiterunnerworker.runsuite(suiterunnerworker.java:52(at org.testng.suiterunnerworker.run(suiterunnerworker.java:84(at org.testng.testng.runsuitesquential(testng.java:1208(at org.testng.testng.runsuiteslocally(testng.java:1137(at org.testng.testng.runsuites(testng.java:1049(at org.testng.testng.run(testng.java:1017(at org.apache.maven.surefire.testng.testngexecutor.run(testngexecutor.java:283( 在 org.apache.maven.surefire.testng.testngxmltestsuite.execute(testngxmltestsuite.java:75( 在 org.apache.maven.surefire.testng.testngprovider.invoke(testngprovider.java:120( 在 org.apache.maven.surefire.booter.forkedbooter.invokeproviderinsameclassloader(forkedbooter.java:384( 在 org.apache.maven.surefire.booter.forkedbooter.runsuitesinprocess(forkedbooter.java:345( 在 org.apache.maven.surefire.booter.forkedbooter.execute(forkedbooter.java:126( 在 org.apache.maven.surefire.booter.forkedbooter.main(forkedbooter.java:418(

嗨,克里希纳,

pfb the Masetest代码。

package generic;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
public  class BaseTest implements Autoconst {
    File file=new File("\\192.168.70.39\IT Share\Automation\ERP Automation\credential.properties");
     Properties prop = new Properties();
    public WebDriver driver;
    @Parameters({"browser"})
    @BeforeMethod
    public void precondition()
    {
        if(browser.equals("chrome"))
        {
        FileInputStream fileInput =null;
        try {
            fileInput = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            prop.load(fileInput);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.setProperty(GECKO_KEY,GECKO_VALUE);
        ChromeOptions options = new ChromeOptions();
        options.setPageLoadStrategy(PageLoadStrategy.NONE);
        driver=new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
        driver.get(prop.getProperty("URL"));
        driver.manage().window().maximize();
        }
    }
    @AfterMethod
    public void postcondition()
    {
        driver.quit();
    }
}

您将testng侦听器和与TestClass相关的注释混合在一起,这就是导致NullPointerException

的原因

我猜您有一个测试类,它也正在扩展BaseTest。为了示例,让我们将该类称为RegressionTest

testng现在创建两个实例:

  • RegressionTest类的1个实例
  • testNgListners类的1个实例。

但要点是,当创建testNgListners实例时,@BeforeMethod@AfterMethod注释根本不会被调用,因为这些注释在侦听器的上下文中没有任何相关性。

要解决此问题,您需要执行以下操作:

  • 重构testNgListners,以免扩展BaseTest
  • 现在在BaseTest中移动浏览器实例化和清理逻辑。
  • 您应该通过testng侦听器管理浏览器实例化,因为每当发生故障时,驱动程序对象也将使用驱动程序对象进行屏幕截图。

以下是修改后的听众的样子:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.Reporter;
public class BrowserManagementListener implements ITestListener {
  private static final String BROWSER = "browser";
  private File file =
      new File("\\192.168.70.39\IT Share\Automation\ERP Automation\credential.properties");
  private Properties prop = new Properties();
  public static RemoteWebDriver getDriver() {
    ITestResult result = Reporter.getCurrentTestResult();
    if (result == null) {
      throw new IllegalStateException("could not detect a valid test result");
    }
    Object object = result.getAttribute(BROWSER);
    if (object == null) {
      throw new IllegalStateException("could not find a browser");
    }
    return (RemoteWebDriver)object;
  }
  @Override
  public void onTestStart(ITestResult result) {
    // This line retrieves the value of
    // <parameter name="browser" value="chrome"/> from your testng suite xml
    String browser = result.getTestContext().getCurrentXmlTest().getParameter("browser");
    if ("chrome".equalsIgnoreCase(browser)) {
      FileInputStream fileInput = null;
      try {
        fileInput = new FileInputStream(file);
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      }
      try {
        prop.load(fileInput);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    ChromeOptions options = new ChromeOptions();
    options.setPageLoadStrategy(PageLoadStrategy.NONE);
    RemoteWebDriver driver = new ChromeDriver();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.manage().window().maximize();
    result.setAttribute(BROWSER, driver);
  }
  @Override
  public void onTestSuccess(ITestResult result) {
    cleanUpBrowser(result);
  }
  @Override
  public void onTestFailure(ITestResult result) {
    Object object = result.getAttribute(BROWSER);
    if (object == null) {
      return;
    }
    RemoteWebDriver driver = (RemoteWebDriver) object;
    File srcFile = driver.getScreenshotAs(OutputType.FILE);
    File destFile = new File("test-output/" + result.getName() + ".png");
    try {
      FileUtils.copyFile(srcFile, destFile);
      System.out.println("Screenshot is been taken for failed test case: " + result.getName());
      System.err.println("Screenshot below" + destFile.getAbsolutePath());
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      cleanUpBrowser(result);
    }
  }
  private void cleanUpBrowser(ITestResult result) {
    Object driver = result.getAttribute(BROWSER);
    if (driver != null) {
      ((RemoteWebDriver) driver).quit();
      result.setAttribute(BROWSER, null);
    }
  }
}

这是测试类的样子

import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
@Listeners(BrowserManagementListener.class)
public class SampleTestClass {
  @Test
  public void testMethod() {
    BrowserManagementListener.getDriver().get("http://www.google.com");
    throw new RuntimeException("Simulating an error");
  }
}

相关内容

  • 没有找到相关文章

最新更新