android.TakeScreenShot Maven / Gradle / Ivy
package android;
import core.internal.EnvironmentInterface;
import core.reports.TestReporter;
import io.appium.java_client.android.AndroidDriver;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.testng.ITestResult;
import java.io.File;
import java.util.UUID;
/**
* Created by Ismail on 6/7/2018.
*/
public class TakeScreenShot {
/*************** Class Methods Section ***************/
// This method capture screenShot on Test Case Fail
public static void captureScreenshotOnFail(ITestResult testResult) {
// Check if test case status is fail
if (testResult.getStatus() == ITestResult.FAILURE) {
// Save the image path to imagePath String variable
String imagePath = captureScreenshot(testResult.getName() + EnvironmentInterface.CURRENT_TIME);
// If image is taken then send it to report test case logger
if (imagePath != null) {
String image = TestReporter.logger.addScreenCapture(imagePath);
TestReporter.info("Test Case Fail, Image Captured.\n" + image);
} else {// Else add error unable to get image and nothing to do
TestReporter.error("Fail to capture image.\n", false);
}
}
}
// This method capture screenShot and return image path string
public static String captureScreenshot(String imageName) {
// return image captured path string
return captureScreenshot(AndroidDriverInitializer.androidDriver, imageName);
}
// This method capture screenShot for each step and return the image as String
public static String captureScreenshotOnStep(){
return captureScreenshot(UUID.randomUUID().toString());
}
// This method capture an image with AndroidDriver for current active tab and return image Path as string
private static String captureScreenshot(AndroidDriver androidDriver, String screenshotName) {
try {
// Initialize TakesScreenshot Object as AndroidDriver Type
TakesScreenshot screenshot = (TakesScreenshot) androidDriver;
// Initialize File and save captured screenShot
// from getScreenshotAs Method to the file
File source = screenshot.getScreenshotAs(OutputType.FILE);
// Save default image Folder Path
String imageFolder = EnvironmentInterface.REPORT_PATH;
// Save default image File Path and name
String imageFile = EnvironmentInterface.SCREEN_SHOT_PATH + screenshotName + ".png";
// Copy captured image to imageFile absolute Path
FileUtils.copyFile(source, new File(imageFolder + imageFile));
return imageFile;
// Return captured image as String
} catch (Throwable throwable) {
// In case fail then return null
return null;
}
}
}