Taking screenshot in appium

Some important points

  1. Screenshot helps us debug the failing tests easily
  2. We can embed the screenshots in the test report
  3. Developers may restrict taking screenshot of the app due to security reasons. In this case, Screenshot will not work
  4. Code to take screenshot in Android and iOS is same

Below example demonstrates how you can take the screenshot.

package org.softpost.ios.simulator;
import io.appium.java_client.TouchAction;
import io.appium.java_client.ios.IOSDriver;
import io.appium.java_client.touch.offset.PointOption;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by Sagar on 10-07-2016.
 */

public class ScreenshotTest {
    IOSDriver driver;
    @Test
    public void test() throws Exception{
        DesiredCapabilities caps = new DesiredCapabilities();
        caps.setCapability("platformName", "iOS");
        caps.setCapability("platformVersion", "11.0");
        caps.setCapability("deviceName", "iPhone 8");
        caps.setCapability("AutomationName" , "XCUITest");
        caps.setCapability("headless" , true);
        caps.setCapability("avd" , "44059DAD-FFCD-47EF-9B9A-0713AC9B6422");
        caps.setCapability("wdaLocalPort", 8100);
       // caps.setCapability("app", "/Users/admin/iosapps/softpost.app");


        caps.setCapability("bundleId", "com.apple.MobileAddressBook");

        try {
            driver = new IOSDriver(new URL("http://0.0.0.0:4723/wd/hub"), caps);
            driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

            WebElement e = driver.findElement(By.xpath("//XCUIElementTypeButton[@name="Add"]"));

            TouchAction action = new TouchAction(driver);
            action.tap( PointOption.point(e.getLocation())).perform();

            Thread.sleep(2000);

            File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(scrFile, new File("s1.jpg"), true);

        }catch (Exception ex){
            ex.printStackTrace();
            System.out.println(driver.getPageSource());
        }finally {
            driver.quit();
        }

    }

}

Web development and Automation testing

solutions delivered!!