尝试使用selenium截取屏幕时出现空指针异常

时间:2016-06-28 14:25:18

标签: java selenium

我编写了一个Java类,它使用selenium webdriver快速通过网站并测试各种功能。我还写了一个单独的类,用于执行takeScreenshot()方法。一旦测试到达执行屏幕​​截图方法的代码,浏览器就会关闭并且J-Unit测试失败并指向我调用takeScreenshot()方法的行。这是一个空指针异常,但我无法弄清楚什么是错误的..我已阅读了很多文章,无法找到答案。我已经阅读了这里的所有帖子,这些帖子确定了如何使用selenium截取屏幕截图...代码如下:

****截图类****

 public class Screenshot {


private WebDriver webDriver;
File source;

public void takeScreenshot() {

    try {
        source = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(source, new File ("/Users/joshuadunn/Desktop/claimsScreenShot.png"));
        System.out.println("Screenshot Taken!!!!");

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

}

然后我创建一个Screenshot对象并执行其takeScreenshot()方法,如下所示:

@Test
public void testClaimsTestToCalcNode() throws Exception {
    driver.get(baseUrl + "/");
    driver.findElement(By.id("becsStartCalculator")).click();
    driver.findElement(By.id("MARITAL_STATUS_false")).click();
    driver.findElement(By.id("btn_next")).click();
    driver.findElement(By.id("HOME_ABROAD_false")).click();

    *** This is where the null pointer is ***
    *******************************
    screenshot.takeScreenshot();
    *******************************


    driver.findElement(By.id("btn_next")).click();
    driver.findElement(By.id("DETAILS_STUDENT_YOU_false")).click();

我希望你理解我的问题!

编辑**** - 这不是重复..我完全知道空指针是什么以及如何修复它。显然我的代码中的某些东西是空的,但我不知道是什么...下面的截图是我得到的唯一错误(stacktrace)

J-Unit error message

1 个答案:

答案 0 :(得分:5)

您正在WebDriver课程中为Screenshot制作新的参考。此WebDriver永远不会被实例化,因此会为您提供NullPointerException。相反,您应该将WebDriver实例作为参数传递给方法。

public class Screenshot {

File source;

public void takeScreenshot(WebDriver webDriver) {

    try {
        source = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);


    FileUtils.copyFile(source, new File ("/Users/joshuadunn/Desktop/claimsScreenShot.png"));
    System.out.println("Screenshot Taken!!!!");

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

}

测试用例:

@Test
public void testClaimsTestToCalcNode() throws Exception {
    driver.get(baseUrl + "/");
    driver.findElement(By.id("becsStartCalculator")).click();
    driver.findElement(By.id("MARITAL_STATUS_false")).click();
    driver.findElement(By.id("btn_next")).click();
    driver.findElement(By.id("HOME_ABROAD_false")).click();

    *** This is where the null pointer is ***
    *******************************
    screenshot.takeScreenshot(driver);
    *******************************


    driver.findElement(By.id("btn_next")).click();
    driver.findElement(By.id("DETAILS_STUDENT_YOU_false")).click();

修改:或者您可以在WebDriver的构造函数中设置Screenshot

public void Screenshot(WebDriver webDriver){
    this.webDriver = webDriver;
}