java - 知识共享 - Selenium - 当您在 TestNG 中使用监听器进行数百个测试时,对失败的测试进行屏幕截图

标签 java selenium webdriver screenshot

我见过很多在 Selenium 测试期间截取屏幕截图的例子,但看起来它们都需要做很多工作。

其中一些示例是使用 try catch block 进行测试,并在 catch block 中添加用于截取屏幕截图的代码。但这里我们必须用 try catch block 包围所有测试。

另一个例子是仅使用监听器,但我们需要为每个测试都有一个单独的监听器,当您有很多测试用例时,这实际上是不可能的。

因此,我仅使用监听器来完成此操作,但所有测试仅使用一个监听器。测试失败时会进行截图。

我出于知识目的而分享它,我准备接受您的评论或您建议的任何改进。另外,如果我的代码有任何错误,请告诉我。

当您需要运行大量测试时,如果有更好的截图方法,请建议我。

谢谢。

最佳答案

这里我有四种文件。

  1. TestNG xml
  2. TestBoxNew.java(TestNGExmaples 包中的 Selenium 脚本)
    RadioButtons.java(另一个包中的 Selenium 脚本 测试NG示例1)
  3. Initializing.java(包含一个 MAP,其中包含类名和 司机)
  4. Listeners.java(实现iTestListeners接口(interface))

TestNG xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
  <listeners>
    <listener class-name="TestNGExamples.Listeners"/>
  </listeners>
  <test thread-count="5" name="Test">
    <classes>
      <class name="TestNGExamples.TextBoxNew"/>
      <class name="TestNGExamples1.RadioButtons"/>
    </classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->

下面是两个脚本TextBoxNew.java和RadioButtons.java。 在每个方法中,我都将驱动程序添加到 Initializing.java 中声明的映射中。

TestNGExamples.Initializing.map1.put("TestNGExamples1.RadioButtons", driver);

如果测试成功执行,我会在退出驱动程序之前将其从 map 中删除。

TestNGExamples.Initializing.map1.remove("TestNGExamples1.RadioButtons");

TextBoxNew.java

在这个测试中,我有四个测试 TextBox1()、TextBox2()、TextBox3() 和 TextBox4()。我通过在 findElement 方法中传递错误的名字值故意使前三个失败。所以这些将产生屏幕截图。

package TestNGExamples;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class TextBoxNew {

    @Test
    public void TextBox1() throws InterruptedException{
        System.setProperty("webdriver.gecko.driver", "C:\\BrowserDrivers\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        TestNGExamples.Initializing.map1.put("TestNGExamples.TextBoxNew", driver);
        driver.get("file:///D:/Selenium%20Course/Java/index.html");
        //Thread.sleep(2000);
        driver.findElement(By.id("firstnam")).sendKeys("Subbu");
        TestNGExamples.Initializing.map1.remove("TestNGExamples.TextBoxNew");
        //Thread.sleep(2000);
        driver.quit();
    }

    @Test
    public void TextBox2() throws InterruptedException {
        System.setProperty("webdriver.gecko.driver", "C:\\BrowserDrivers\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        TestNGExamples.Initializing.map1.put("TestNGExamples.TextBoxNew", driver);
        driver.get("file:///D:/Selenium%20Course/Java/index.html");
        //Thread.sleep(2000);
        driver.findElement(By.xpath("//input[@color='re']")).sendKeys("Venkat");
        //Thread.sleep(2000);
        TestNGExamples.Initializing.map1.remove("TestNGExamples.TextBoxNew");
        driver.quit();
    }

    @Test
    public void TextBox3() throws InterruptedException {
        System.setProperty("webdriver.gecko.driver", "C:\\BrowserDrivers\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        TestNGExamples.Initializing.map1.put("TestNGExamples.TextBoxNew", driver);
        driver.get("file:///D:/Selenium%20Course/Java/index.html");
        //Thread.sleep(2000);
        driver.findElement(By.id("first nam")).sendKeys("Ganesh");
        //Thread.sleep(2000);
        TestNGExamples.Initializing.map1.remove("TestNGExamples.TextBoxNew");
        driver.quit();
    }

    @Test
    public void TextBox4() throws InterruptedException {
        System.setProperty("webdriver.gecko.driver", "C:\\BrowserDrivers\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        TestNGExamples.Initializing.map1.put("TestNGExamples.TextBoxNew", driver);
        driver.get("file:///D:/Selenium%20Course/Java/index.html");
        //Thread.sleep(2000);
        driver.findElement(By.xpath("//input[starts-with(@id,'last')]")).sendKeys("Rajesh");
        //Thread.sleep(2000);
        TestNGExamples.Initializing.map1.remove("TestNGExamples.TextBoxNew");
        driver.quit();
    }
}

RadioButtons.java

这包含五个方法,我故意通过向 findElement 方法传递错误的值来使第一个方法失败。这将生成一张屏幕截图。

package TestNGExamples1;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class RadioButtons {
    @Test
    public static void RadioButton1() throws InterruptedException {
        System.setProperty("webdriver.gecko.driver", "C:\\BrowserDrivers\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        TestNGExamples.Initializing.map1.put("TestNGExamples1.RadioButtons", driver);
        driver.get("file:///D:/Selenium%20Course/Java/index.html");     
        //Thread.sleep(2000);
        driver.findElement(By.xpath("//input[@value='femal']")).click();
        Thread.sleep(2000);
        TestNGExamples.Initializing.map1.remove("TestNGExamples1.RadioButtons");
        driver.quit();
    }
    @Test
    public static void RadioButton2() throws InterruptedException {
        System.setProperty("webdriver.gecko.driver", "C:\\BrowserDrivers\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        TestNGExamples.Initializing.map1.put("TestNGExamples1.RadioButtons", driver);
        driver.get("file:///D:/Selenium%20Course/Java/index.html");
        //Thread.sleep(2000);
        int no_radio_buttons = driver.findElements(By.xpath("//input[@name='gender']")).size();
        System.out.println("No. of radio buttons are "+no_radio_buttons);
        Thread.sleep(2000);
        TestNGExamples.Initializing.map1.remove("TestNGExamples1.RadioButtons");
        driver.quit();
    }

    @Test
    public static void RadioButton3() throws InterruptedException {
        System.setProperty("webdriver.gecko.driver", "C:\\BrowserDrivers\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        TestNGExamples.Initializing.map1.put("TestNGExamples1.RadioButtons", driver);
        driver.get("file:///D:/Selenium%20Course/Java/index.html");
        //Thread.sleep(2000);
        int no_radio_buttons = driver.findElements(By.xpath("//input[@name='gender']")).size();
        System.out.println("No. of radio buttons are "+no_radio_buttons);
        for(int j=0; j<10; j++) {
            for(int i=0; i<no_radio_buttons; i++) {
                driver.findElements(By.xpath("//input[@name='gender']")).get(i).click();
            }
        }
        //Thread.sleep(2000);       
        TestNGExamples.Initializing.map1.remove("TestNGExamples1.RadioButtons");
        driver.quit();
    }

    @Test
    public static void RadioButton4() throws InterruptedException {
        System.setProperty("webdriver.gecko.driver", "C:\\BrowserDrivers\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        TestNGExamples.Initializing.map1.put("TestNGExamples1.RadioButtons", driver);
        driver.get("file:///D:/Selenium%20Course/Java/index.html");
        //Thread.sleep(2000);
        int no_radio_buttons = driver.findElements(By.xpath("//input[@name='gender']")).size();
        System.out.println("No. of radio buttons are "+no_radio_buttons);
        for(int i=0; i<no_radio_buttons; i++) {
            String str = driver.findElements(By.xpath("//input[@name='gender']")).get(i).getAttribute("value");
            System.out.println(str);
        }
        //Thread.sleep(2000);       
        TestNGExamples.Initializing.map1.remove("TestNGExamples1.RadioButtons");
        driver.quit();

    }

    @Test
    public static void RadioButton5() throws InterruptedException {
        System.setProperty("webdriver.gecko.driver", "C:\\BrowserDrivers\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        TestNGExamples.Initializing.map1.put("TestNGExamples1.RadioButtons", driver);
        driver.get("file:///D:/Selenium%20Course/Java/index.html");
        //Thread.sleep(2000);
        int no_radio_buttons = driver.findElements(By.xpath("//input[@name='gender']")).size();
        System.out.println("No. of radio buttons are "+no_radio_buttons);
        for(int i=0; i<no_radio_buttons; i++) {
            String str = driver.findElements(By.xpath("//input[@name='gender']")).get(i).getAttribute("value");
            if(str.equals("other")) {
                driver.findElements(By.xpath("//input[@name='gender']")).get(i).click();
            }
        }
        //Thread.sleep(2000);
        TestNGExamples.Initializing.map1.remove("TestNGExamples1.RadioButtons");
        driver.quit();
    }
}

初始化.java

可能这个名字看起来有欺骗性,但我只是用它在这个类中创建一个 map 。

package TestNGExamples;

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

import org.openqa.selenium.WebDriver;

public class Initializing {
    public static Map<String, WebDriver> map1 = new HashMap<String, WebDriver>();
}

Listener.java

现在来到监听器,我已经在 onTestFailure 方法中实现了屏幕截图代码。首先,我们使用以下行获取 packagename.classname

String clname = result.getInstanceName();

我们可以通过以下行获取存储在Initializing.java的映射中的驱动程序对象。

WebDriver driver = TestNGExamples.Initializing.map1.get(clname);

还可以使用以下行获取方法名称,因为我们使用 packagename.classname.methodname 存储图像。

String mthname = result.getName();

现在截取屏幕截图。

File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(src, new File("D:\\TestNGScreenshots\\"+clname+"."+mthname+".png"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

最后从 map 上删除驱动程序并退出。

TestNGExamples.Initializing.map1.remove(clname);
driver.quit();

完整代码:

package TestNGExamples;

import java.io.File;
import java.io.IOException;

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 org.apache.commons.io.FileUtils;

public class Listeners implements ITestListener{

    @Override
    public void onTestStart(ITestResult result) {
        // TODO Auto-generated method stub
        System.out.println("Test Started");
    }

    @Override
    public void onTestSuccess(ITestResult result) {
        // TODO Auto-generated method stub
        System.out.println("Test Successful");
    }

    @Override
    public void onTestFailure(ITestResult result) {
        // TODO Auto-generated method stub
        String clname = result.getInstanceName();
        System.out.println("Class Name is "+clname);
        WebDriver driver = TestNGExamples.Initializing.map1.get(clname);
        String mthname = result.getName();
        System.out.println("Method Name is "+mthname);
        File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(src, new File("D:\\TestNGScreenshots\\"+clname+"."+mthname+".png"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        TestNGExamples.Initializing.map1.remove(clname);
        driver.quit();
        System.out.println("Test Failed");
    }

    @Override
    public void onTestSkipped(ITestResult result) {
        // TODO Auto-generated method stub
        System.out.println("Test Skipped");
    }

    @Override
    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
        // TODO Auto-generated method stub
        System.out.println("Test failed but with in Success Percentage");
    }

    @Override
    public void onStart(ITestContext context) {
        // TODO Auto-generated method stub
        System.out.println("Test Started Beginning");
    }

    @Override
    public void onFinish(ITestContext context) {
        // TODO Auto-generated method stub
        System.out.println("Test Started Ending");
    }
}

仅此而已。如果您有任何意见、问题或任何改进,请告诉我。

Failed Tests Images

关于java - 知识共享 - Selenium - 当您在 TestNG 中使用监听器进行数百个测试时,对失败的测试进行屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52446365/

相关文章:

java - 我看不到数据,也看不到我创建的 sqlite 表

java - 在 Netbeans 或 Eclipse 中引用第 3 方 .jar

java - FluentWait类型不是通用的;无法通过Selenium和Java使用FluentWait类的参数<WebDriver>错误对它进行参数化

java - 我收到 NoSuchElement 异常错误

java - 使用 Selenium 2 将本地镜像注入(inject)/加载到当前网页

python - 如何使用 Selenium 的 webdriver 和 Python 检查网页内容是否已更改?

webdriver - 使用 selenium web 驱动程序时如何在测试执行后保持浏览器打开

java - 具有特定格式的 XMLGregorianCalendar 日期

java - 内容相同但 JUnit 测试失败(IntelliJ)

c# - 如何使用 C# 中的 Selenium chrome 驱动程序从网页打印到控制台的 URL 列表?