Taking screenshot in Appium

Now let us learn how to take the screenshot in Appium.

We can take the screenshot of an Android app as illustrated in below code. Note that we are using selenium API for taking a screenshot.

package nativeapptests;

import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

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

public class LaunchCalculatorOnAndroidPhone
{
    private WebDriver driver;

    @Test
    public void loadingSinglePageTest() throws Exception{
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("platformName", "Android");
        capabilities.setCapability("platformVersion", "4.4.4");
        capabilities.setCapability("deviceName", "sagarcell");
        capabilities.setCapability("browser_Name", "Android");
       // capabilities.setCapability("app", "chrome");
        capabilities.setCapability("appPackage", "com.sec.android.app.popupcalculator");
        capabilities.setCapability("appActivity","com.sec.android.app.popupcalculator.Calculator");
        //capabilities.setCapability("browserName", "Chrome");

        driver = new RemoteWebDriver(new URL("https://127.0.0.1:4723/wd/hub"), capabilities) {
        };
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.findElement(By.name("2")).click();

        driver.findElement(By.name("+")).click();

        driver.findElement(By.name("6")).click();

        driver.findElement(By.name("=")).click();
        WebElement txt= driver.findElement(By.className("android.widget.EditText"));

        File f = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(f,
                    new File("C:\\Users\\Sagar\\IdeaProjects\\AndroidAutomation\\abc.png"));
        }catch(Exception ex){
            System.out.println("Exception " + ex.toString());
        }
        String p = txt.getText();
        String replacement = p.replaceAll("\t|\n|\r", "");
        Assert.assertTrue("",replacement.equalsIgnoreCase("2+6=8"));
        driver.quit();
        //quit the browser
    }
}

Here is the screenshot of calculator.

Calculator screenshot using Appium - Selenium

Calculator screenshot using Appium – Selenium

Please note that if you are using selenium grid, you will have to use below code to take the screenshot.

WebDriver augmentedDriver = new Augmenter().augment(driver);
  File f = ((TakesScreenshot) augmentedDriver ).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(f,
                    new File("C:\\Users\\Sagar\\IdeaProjects\\AndroidAutomation\\abc.png"));
        }catch(Exception ex){
            System.out.println("Exception " + ex.toString());
        }

You may also like...