知识共享-Selenium-使用TestNG中的侦听器进行100项测试时,为失败的测试拍摄屏幕截图

时间:2018-09-21 14:55:40

标签: java selenium webdriver screenshot

我已经看到了许多在硒测试期间进行屏幕截图的示例,但是看起来它们确实确实需要大量的工作。

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

另一个示例仅使用侦听器,但是我们需要为每个测试使用单独的侦听器,而在您有大量测试用例的情况下,这实际上是不可能的。

因此,我仅使用侦听器来完成此操作,但所有测试仅使用一个侦听器。测试失败时,它将截取屏幕截图。

我出于知识目的共享它,并准备接受您的评论或您提出的任何改进。另外请告诉我我的代码是否有错误。

如果要运行大量测试,如果有更好的方法来截取屏幕截图,请建议我。

谢谢。

1 个答案:

答案 0 :(得分:0)

这里我有四种文件。

  1. TestNG xml
  2. TestBoxNew.java(程序包TestNGExmaples中的硒脚本)
    RadioButtons.java(另一个包中的硒脚本 TestNGExamples1)
  3. Initializing.java(包含一个包含类名和名称的MAP 驱动程序)
  4. Listeners.java(已实现iTestListeners接口)

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);

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

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();
    }
}

Initializing.java

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

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();
        }

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

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