To start with, I am using java.
Here is the screenshot method:
public void screenshot(String path_screenshot) throws IOException{
File srcFile=driver.getScreenshotAs(OutputType.FILE);
String filename=UUID.randomUUID().toString();
File targetFile=new File(path_screenshot + filename +".jpg");
FileUtils.copyFile(srcFile,targetFile);
}
- The method above basically takes a screenshot of the entire screen. Feel free to modify it to do what you want...
I have yet to figure out how to take a screenshot of a MobileElement object only and not the entire screen...,
the way I used to be able to take a screenshot of a View object in Robotium...
But assuming you are able to take a jpg screenshot of your entire screen in your appium test, you can then use these snippets of code to do an image comparison in java:
import android.graphics.Bitmap;
import java.nio.ByteBuffer;
import java.nio.ByteBuffer;
import java.util.Arrays;
public static boolean imagesEquals(Bitmap bitmap1, Bitmap bitmap2) {
ByteBuffer buffer1 = ByteBuffer.allocate(bitmap1.getHeight() * bitmap1.getRowBytes());
bitmap1.copyPixelsToBuffer(buffer1);
ByteBuffer buffer2 = ByteBuffer.allocate(bitmap2.getHeight() * bitmap2.getRowBytes());
bitmap2.copyPixelsToBuffer(buffer2);
return Arrays.equals(buffer1.array(), buffer2.array());
}
The method above compares 2 bitmaps and checks to see if they are equal. Java magic
But now you ask, how do I create bitmaps in my code?
Here is an example that shows you how to create 2 bitmaps, one of the screenshot and one of the image that will be compared:
import android.graphics.BitmapFactory;
Bitmap bitmap1 = BitmapFactory.decodeFile("/path/to/screeshot/screenshot.jpg");
Bitmap bitmap2 = BitmapFactory.decodeFile("/path/to/image_that_will_be_compared/assertionImage.jpg");
then once you have the bitmap objects created, simply use the imagesEquals method above to return a boolean value:
//Compare the two images and return the result
boolean areImagesEqual = MobilUtils.imagesEquals(mBitmap1, mBitmap2);
In this case I created a static method and called the class + the method, passed in the two bitmap objects into the method and viola, you get a true or false value.