尝试使用硒截屏时出现空指针异常

Jos*_*osh -2 java selenium

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

****屏幕截图类****

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

}
Run Code Online (Sandbox Code Playgroud)

然后,我创建一个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();
Run Code Online (Sandbox Code Playgroud)

希望你能理解我的问题!

编辑****-这不是重复的。我完全知道什么是空指针以及如何将其固定。显然,我的代码中的某些内容通过null传递,但我不知道...下面的屏幕快照是我得到的唯一错误(stacktrace)

J-Unit错误消息

Rem*_*coW 6

您正在为一个新的参考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();
    } 
}

}
Run Code Online (Sandbox Code Playgroud)

和测试用例:

@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();
Run Code Online (Sandbox Code Playgroud)

编辑:或者,您可以WebDriver在的构造函数中设置Screenshot

public void Screenshot(WebDriver webDriver){
    this.webDriver = webDriver;
}
Run Code Online (Sandbox Code Playgroud)