- Selenium Framework Design in Data-Driven Testing
- Carl Cocchiaro
- 235字
- 2025-02-18 04:59:04
The compare image method
Finally, after capturing the screen or WebElement, users can do a pixel or size comparison of the two images. It is difficult to keep the bitmaps in sync from browser-to-browser, or mobile device-to-mobile device, but the method is here for argument's sake:
public enum RESULT { Matched, SizeMismatch, PixelMismatch }
/**
* compareImage - method to compare 2 images
*
* @param expFile - the expected file to compare
* @param actFile - the actual file to compare
* @return RESULT
* @throws Exception
*/
public static RESULT compareImage(String expFile,
String actFile)
throws Exception {
RESULT compareResult = null;
Image baseImage = Toolkit.getDefaultToolkit().getImage(expFile);
Image actualImage = Toolkit.getDefaultToolkit().getImage(actFile);
// get pixels of image
PixelGrabber baseImageGrab =
new PixelGrabber(baseImage,0,0,-1,-1,false);
PixelGrabber actualImageGrab =
new PixelGrabber(actualImage,0,0,-1,-1,false);
int [] baseImageData = null;
int [] actualImageData = null;
// get pixels coordinates of base image
if ( baseImageGrab.grabPixels() ) {
int width = baseImageGrab.getWidth();
int height = baseImageGrab.getHeight();
baseImageData = new int[width * height];
baseImageData = (int[])baseImageGrab.getPixels();
}
// get pixels coordinates of actual image
if ( actualImageGrab.grabPixels() ) {
int width = actualImageGrab.getWidth();
int height = actualImageGrab.getHeight();
actualImageData = new int[width * height];
actualImageData = (int[])actualImageGrab.getPixels();
}
// test for size mismatch, then pixel mismatch
if ( (baseImageGrab.getHeight() != actualImageGrab.getHeight()) ||
(baseImageGrab.getWidth() != actualImageGrab.getWidth()) ) {
compareResult = RESULT.SizeMismatch;
}
else if ( java.util.Arrays.equals(baseImageData,actualImageData) ) {
compareResult = RESULT.Matched;
}
else {
compareResult = RESULT.PixelMismatch;
}
return compareResult;
}