Getting error "java.lang.NullPointerException" while taking screenshot for failure in mobile app test execution

I have used following code —
For capturing screenshot
public CaptureScreenshot(AndroidDriver driver) {
super(driver);
// TODO Auto-generated constructor stub
}

	//public static AndroidDriver<MobileElement> driver;
     // function to capture screenshot.
	 public void captureScreenShot(String fileName){
	String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date(0));
	 String destination = System.getProperty("user.dir") + "/screenshots/" +fileName+".png";
	 
	 TakesScreenshot takeScreenshot =  ((TakesScreenshot)this.driver);
	  File srcFile = takeScreenshot.getScreenshotAs(OutputType.FILE);
	  File destFile = new File(destination);
	  try {
		  FileUtils.copyFile(srcFile, destFile);
	 
	  System.out.println("Screenshot saved successfully at " + System.currentTimeMillis());
	 }
	 catch (Exception e) 
	    {
	    System.out.println("Exception while taking screenshot "+e.getMessage());
	    }
	 
	 }

For calling function in listener
@Override
public void onTestFailure(ITestResult result) {
Reporter.log(“Status of test result” + result.getStatus());
System.out.println("Testcase failed for " + result.getMethod().getMethodName());
CaptureScreenshot bc = new CaptureScreenshot(null);
bc.captureScreenShot(result.getMethod().getMethodName());
}

Hi can someone please help me for this issue ? Screenshots are not saved for failure while executing test in android device. Pease help me I am stuck. Seems there is some minor issue on my code that I am not able to find out.

The code you’ve posted is really difficult to read for 2 reasons:

  1. You’ve formatted it really strangely. Some of the code has no indentation, some is in a quote, etc.
  2. You’ve left in some commented out code.
  3. You are having trouble with something that is fairly basic, and could easily be searched for on the web.

So for the future, try searching the web first, then if you feel you must ask a question make sure your code is as readable as you can make it, not just cut and pasted from your ide with all your mistakes intact. Really take the time to do the best you can and I think you will find that people respond to you more quickly.

Here is an article I searched up for you:

https://stackoverflow.com/questions/50129071/screenshot-java-code-in-appium-selenium

1 Like

This is your constructor:

And this is the value you pass to it:

  • make sure you take the screenshot before killing appium driver…
1 Like