Image Comparison Using Selenium Shutterbug
Image Comparison Using Selenium Shutterbug will discuss how we can compare 2 screenshots of a particular WebElement or particular web pages while working with selenium.
Major Validations that we generally do in our day to day life is Text comparison in selenium. We always verify expected output value and mark our test cases pass or fail. Let’s take a step forward and compare screens using selenium to make our automation scripts more robust. With ShutterBug we can compare screenshots in our runtime execution
We recommend you to refer our previous blog for better understanding.
To start with it , Add below dependency to maven project or Download jar files here.
<!-- https://mvnrepository.com/artifact/com.assertthat/selenium-shutterbug --> <dependency> <groupId>com.assertthat</groupId> <artifactId>selenium-shutterbug</artifactId> <version>${version}</version> </dependency>
Lets Capture expected image first:
Sample Code:
public class ShutterbugExpectedScreenshot { @Test public void ExpectedScreenshotDesiredName() { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.get("http://automationtesting.in"); Shutterbug.shootPage(driver,ScrollStrategy.BOTH_DIRECTIONS,500,true).withName("Expected").save(); driver.quit(); } }
Above code will take full page screenshot and saves with name as “Expected”
Screenshot Comparison:
Syntax:
Shutterbug.shootPage(driver,ScrollStrategy.BOTH_DIRECTIONS,500,true). withName("<desiredName>").equals(<ExpectedImage>,<Deviation Ratio>);
In above syntax, shoot page is a method which captures screenshot by scrolling page for specific time. withName() method assigns desired name to screenshot take by shootpage() method. Equals method compares screenshots with deviation ratio.
Sample Code:
public class ShutterbugCompareScreenshot { @Test public void capturefullPageScreenshotwithDesiredName() { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.get("http://automationtesting.in"); File image = new File(".\\screenshots\\Expected.png"); BufferedImage expectedImage = ImageIO.read(image); boolean status = Shutterbug.shootPage(driver,ScrollStrategy.BOTH_DIRECTIONS,500,true).withName("Actual").equals(expectedImage,0.1); Assert.assertTrue(status); driver.quit(); } }
In above code we are buffering expected image using BufferedImage class and Then we are comparing with Actual screenshot taken using equals method in shutterbug. After that we are verifying test case with assert statement
Reference Link:
https://github.com/assertthat/selenium-shutterbug.