Friday 7 September 2018

Compare Images in Selenium Test

Visual / UI Validation of web pages across different browsers & devices is very important these days as more and more applications are getting web enabled. And most of the websites are eyeing on 'Responsive Web Design' to create a single website across multiple resolutions.

This type of testing is usually performed manually. However, now you can automate these type of tests to an extent using different image comparison libraries like Thumbnailator, Slenium-Shutterbug, ImageMagick Applitools Eyes etc.

Using these libraries, both Functional Testing & Visual Testing can go hand-in-hand without having to maintain separate set of scripts.
One such example using Image-comparison.jar based on Thumbnailator library is as below:


Steps:






NOTE: If someone wants to ignore the small changes without having the tests fail, then the parameter 'Threshold' accepted by ImageComparison method can be tweaked along with the x,y pixel size if necessary.


Code Snippet:


//Variables
WebDriver driver1 = new ChromeDriver();
WebDriver driver2 = new ChromeDriver();
String imgOriginal = "c:\\screens\\Original.jpg";
String imgToCompare = "c:\\screens\\Altered.jpg";
String DiffImage = "c:\\screens\\DiffImage.jpg";


driver1.get("http://toolsqa.com");
driver1.manage().window().maximize();
Thread.sleep(3000);
//Take original screenshot of a web page
File scrFile1 = ((TakesScreenshot)driver1).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile1, new File(imgOriginal));

driver2.get("http://toolsqa.com");
driver2.manage().window().maximize();
Thread.sleep(3000);

//Edit the web element color to validate the difference
WebElement elm = driver2.findElement(By.xpath("//*[@id='primary-menu']/li[1]/a/span[1]/span/span"));
JavascriptExecutor jse = (JavascriptExecutor)driver2;
jse.executeScript("arguments[0].setAttribute('style','background: black;');", elm);
//Take the edited screenshot of a web page
File scrFile2 = ((TakesScreenshot)driver2).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile2, new File(imgToCompare));

//Compare the two images captured above.
//ImageComparison(pixelPerBlockX,pixelPerBlockY,Threshold)
ImageComparison imageComparison = new ImageComparison(20,20,0.15);
if(imageComparison.fuzzyEqual(imgOriginal,imgToCompare,DiffImage))
System.out.println("Images are Similar.");
else
System.out.println("Images are not Similar.");



References:


No comments:

Post a Comment