javaseleniumselenium-webdrivertakesscreenshot

How to wrap this "TakesScreenshot" function into method?


I am using this code to capture screenshot in selenium webdriver with JAVA:

  File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    
    
    try {
        FileUtils.copyFile(screenshot, new File("C:\\projectScreenshots\\homePageScreenshot.png"));
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }

But when I wrap this code into function like below, then it throws me NullpointerException.

public static void TakesScreenshot()
{
            

File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
     try {
            FileUtils.copyFile(screenshot, new File("C:\\projectScreenshots\\homePageScreenshot.png"));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
}

Solution

  • I solved NullpointerException by using this below function:

    public static void takeScreenshot(String file, WebDriver driver) {
        try{
            File scrFile=((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(scrFile, new File("C:\\Users\\"+file+".png"));
        } catch(IOException ioe) {
            ioe.getStackTrace();
        }
    }
    

    To call the above function, we need to use this line in the script:

    takeScreenshot("Screenshot", driver);