How to capture and compare multiple screenshots in selenium java
Before executing the below code, make sure that pom is updated with the required dependencies.
We are using Ashot for capturing and comparing screenshots.
Refer to maven repository for Ashot dependency. If you are not using the maven project, you can download the jar for the same.
Here is the link
Add this dependency to pom.xml or download the jar and add it to JAVA build path.
<code>
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import org.openqa.selenium.WebDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.comparison.ImageDiff;
import ru.yandex.qatools.ashot.comparison.ImageDiffer;
public class ScreenCapture {
static BufferedImage baseline;
static BufferedImage testcases;
public static void baselines(WebDriver driver) throws IOException, InterruptedException
{
Date d = new Date();
System.out.println(d.toString());
Thread.sleep(1000);
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH-mm-ss”); /* Your each screenshot will be taken as this format “Year-Month-Date-Hours-Minutes-Seconds”*/
Screenshot screenshot = new AShot().takeScreenshot(driver);
ImageIO.write(screenshot.getImage(),”PNG”,new File(“desired-path”+sdf.format(d)+”.png”));
baseline= ImageIO.read(new File(“desired-path”+sdf.format(d)+”.png”));
}
public static void testcasepictures(WebDriver driver) throws IOException, InterruptedException
{
Date d = new Date();
System.out.println(d.toString());
Thread.sleep(2000);
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HHmmss”); ;
Screenshot screenshot = new AShot().takeScreenshot(driver);
ImageIO.write(screenshot.getImage(),”PNG”,new File(“desired-path”+sdf.format(d)+”.png”));
testcases= ImageIO.read(new File(“desired-path”+sdf.format(d)+”.png”));
}
public static void compare() {
ImageDiffer imgDiff = new ImageDiffer();
ImageDiff diff = imgDiff.makeDiff(baseline, testcases);
if(diff.hasDiff()==true)
{
System.out.println(“Images are Not Same”);
}
else {
System.out.println(“Images are Same”);
}
}
}
</code>
Make sure that you have added this code to a separate class “ScreenCapture” inside the package where you want to perform these actions.
Now you can call these function multiple times in your main code inside same package:
ScreenCapture.baselines(driver);
ScreenCapture.testcasepictures(driver);
ScreenCapture.compare();
Happy Testing!