Site Loader
Auckland, New Zealand
In the last post we discussed how to automate android native mobile application using Appium, in this post we will start our discussion to automate android hybrid application using Appium. In this post we will discuss automating an android hybrid application which we developed in Robotium series, which you can checkout here For automating an hybrid application need to do the following
  • Desired capability
  • Identify the control (elements of UI)
  • Write the code to perform operation
Here is the complete code for the above discussion
public class FirstAppiumTest {

	// Create instance for Appium Driver
	AppiumDriver driver;

	@BeforeClass
	public void Setup() throws MalformedURLException {

		DesiredCapabilities cap = new DesiredCapabilities();
		cap.setCapability(MobileCapabilityType.DEVICE_NAME, "donatello");
		cap.setCapability(MobileCapabilityType.APP_PACKAGE, "com.example.executeautomationapp");

		driver = new AndroidDriver(new URL(
				"http://127.0.0.1:4723/wd/hub"), cap);

	}

	@Test
	public void SimpleTest() {

                driver.context("WEBVIEW_com.example.executeautomationapp");
		// Navigate to google.cocm
		driver.get("http://www.google.com");
		// Search 
		driver.findElementByName("q").SendKeys("execute automation");
		// Click button 
		driver.findElementByName("btnG").click();
	}
}
Here is the complete video of the above discussion. Thanks for reading the post and watching the video !!! Please leave your comments and let me know if there is anything I should update in this post. Thanks, Karthik KK

Post Author: Karthik kk

11 Replies to “Automating hybrid app using Appium”

  1. Hi There ,

    Hope you are doing well. Need a help regarding the issue we are facing with Appium.

    Basically i am new to appium ,playing with flipkart mobile app.

    Is there a way to extract the list of products present on the mobile screen. Say for example if there are 10 mobile phone ,out of which 3 are displayed on the current mobile screen, user has to scroll down to view remaining 7 mobile phones.

    Can we build the list with all 10 mobile phones. When i tried , only the products that are visible of the screen are available in the list ie 3 mobile phone in above stated example.

    Any inputs much appreciated.Please advise. Thank you

  2. I went through this video for switching the context on Appium 1.4.16 and I am not able to switch context to WEBVIEW. Can you help me in this ?

  3. Hi Karthik KK,

    Thanks for your video..

    i was stuck to access Hybrid app using Appium,after watching the video i am able to access the app in Android device,

    Many Thanks… 🙂
    Vinod Rohilla

  4. Hello Kartik, I have learnt automation from your posts and videos. But I am stuck badly with one of the thing, please help me…….
    I am not able to click on button of hybrid app using aooium? tried many ways but still I am not able to do so.

      1. Yes Kartik I did, here’s my code –
        ————————————————-

        package com.TMA;

        import java.io.File;
        import java.net.MalformedURLException;
        import java.net.URL;
        import java.util.Set;

        import org.openqa.selenium.By;
        import org.openqa.selenium.NoSuchElementException;
        import org.openqa.selenium.TimeoutException;
        import org.openqa.selenium.WebElement;
        import org.openqa.selenium.remote.CapabilityType;
        import org.openqa.selenium.remote.DesiredCapabilities;
        import org.openqa.selenium.support.ui.ExpectedConditions;
        import org.openqa.selenium.support.ui.WebDriverWait;
        import org.testng.Assert;
        import org.testng.annotations.AfterClass;
        import org.testng.annotations.AfterMethod;
        import org.testng.annotations.BeforeClass;
        import org.testng.annotations.BeforeMethod;
        import org.testng.annotations.Test;
        import org.testng.asserts.SoftAssert;

        import io.appium.java_client.AppiumDriver;
        import io.appium.java_client.android.AndroidDriver;

        public class TmaAutomate {
        private StringBuffer verificationErrors = new StringBuffer();

        private SoftAssert softAssert;
        boolean testCaseResult;

        WebDriverWait wait;
        public AppiumDriver androidDriver;
        DesiredCapabilities capabilities;

        private By username;
        private By password;
        private By signInButton;
        private By showHidePasswordButton;
        private By buttons;
        private By taskListScreenTitleBar;
        private By taskCommentsButton;
        private By commentScreenTitleBar;

        private By webView;

        @BeforeClass(alwaysRun = true)
        public void setUp() throws Exception {
        System.out.println(“In before class”);
        }

        @BeforeMethod
        public void beforeTest() {
        try {
        Thread.sleep(2000);
        } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        }
        System.out.println(“In before test”);
        softAssert = new SoftAssert();
        testCaseResult =true;

        startAppium();
        wait = new WebDriverWait(androidDriver,300);
        //——————————————————

        webView = By.className(“android.webkit.WebView”);
        wait.until(ExpectedConditions.visibilityOfElementLocated(webView));

        Set availableContexts = androidDriver.getContextHandles();
        System.out.println(“Total No of Context Found After we reach to WebView = “+ availableContexts.size());
        System.out.println(“Context Name is “+ availableContexts);
        for(String context : availableContexts) {
        if(context.contains(“WEBVIEW”)){
        System.out.println(“Context Name is ” + context);
        // 4.3 Call context() method with the id of the context you want to access and change it to WEBVIEW_1
        //(This puts Appium session into a mode where all commands are interpreted as being intended for automating the web view)
        androidDriver.context(context);
        break;
        }
        }
        try {
        Thread.sleep(4000);
        } catch (InterruptedException e) {
        e.printStackTrace();
        }
        username = By.id(“textemailid”);
        password = By.id(“textpassword”);
        buttons = By.id(“btnshowpassword”);
        signInButton = By.id(“btnlogin”);
        //androidDriver.findElementById(“btnLogin”).click();
        //androidDriver.findElementById(“id/btnLogin”).click();

        // showHidePasswordButton = By.id(“com.decos.flo.acc:id/txtTitle”); /* need ids for all elements*/

        taskListScreenTitleBar = By.xpath(“//android.view.View[@text=’Task List – My Tasks’]”);
        taskCommentsButton = By.xpath(“//android.widget.Button[@index=’0′]”);

        commentScreenTitleBar = By.xpath(“//android.view.View[@text=’Comments’]”);

        System.out.println(“– App is launched… Appium test can start here…”);
        try {
        Thread.sleep(4000);
        } catch (InterruptedException e) {
        e.printStackTrace();
        }

        System.out.println(“wait complete”);

        }

        private void startAppium() {
        System.out.println(“- Setting up appium test pre-requisites to create a session of JoinTMA…”);
        File classpathRoot = new File(System.getProperty(“user.dir”));
        File appDir = new File(classpathRoot, “/tmaapk/”);
        File app = new File(appDir, “android-debug(1).apk”);
        // File app = new File(appDir, “tma.apk”);

        capabilities = new DesiredCapabilities();
        // capabilities.setCapability(CapabilityType.BROWSER_NAME, “chrome”);
        //capabilities.setCapability(“autoWebview”, true);
        capabilities.setCapability(“automationName”, “selendroid”);
        capabilities.setCapability(“deviceName”, “4d00d2115fe4400d”);
        capabilities.setCapability(“platformVersion”, “6.0”);
        capabilities.setCapability(“platformName”, “Android”);
        capabilities.setCapability(“app”, app.getAbsolutePath());
        capabilities.setCapability(“appPackage”, “com.decos.joinasia.tma”);
        capabilities.setCapability(“appActivity”, “com.decos.joinasia.tma.MainActivity”);
        // capabilities.setCapability(“noReset”,”false”);
        capabilities.setCapability(“fullReset”,”true”);
        capabilities.setCapability(“newCommandTimeout”,”0″);

        System.out.println(“– Completed doing setup.”);
        System.out.println(“- Start Appium and Launching your application…”);

        try {
        androidDriver = new AndroidDriver(new URL(“http://192.168.1.4:5555/wd/hub”), capabilities);
        } catch (MalformedURLException e1) {
        e1.printStackTrace();
        }

        }

        @AfterMethod
        public void afterTest() {
        System.out.println(“In After Test”);
        try {
        androidDriver.quit();

        Thread.sleep(5000);
        } catch (Exception e) {
        System.out.println(e.getMessage());
        }
        }

        @Test
        public void testSuccessfulTMALogin() {

        try {
        Thread.sleep(1000);
        } catch (InterruptedException e1) {
        e1.printStackTrace();
        }
        System.out.println(“Verifying loging-in with valid credentials login and navigate to Dashboard successfully”);
        softAssert.assertTrue(isDisplayedOnPage(username), “Navigation to Login Screen failed after app launch.”);

        loginActions(“Reetesh”, “123@decos”);

        wait = new WebDriverWait(androidDriver, 20);
        wait.until(ExpectedConditions.visibilityOfElementLocated(taskListScreenTitleBar));

        softAssert.assertEquals(readScreenBarTitle(taskListScreenTitleBar), “Task List – My Tasks”, “User Login failed and hence is not navigated to Dashboard. Screen Title do not match .. “);

        try {
        softAssert.assertAll();
        }catch (Error e) {
        verificationErrors.append(“\n ” + e.toString());
        testCaseResult = false;

        }
        Assert.assertTrue(testCaseResult, “\n Testcase Failed!, ” + “\n” + verificationErrors.toString());
        }

        // @Test
        public void viewCommentsOnTaskListScreen() {

        try {
        Thread.sleep(1000);
        } catch (InterruptedException e1) {
        e1.printStackTrace();
        }
        System.out.println(“Verifying loging-in with valid credentials login and navigate to Dashboard successfully”);

        softAssert.assertTrue(isDisplayedOnPage(username), “Navigation to Login Screen failed after app launch.”);

        loginActions(“Reetesh”, “123@decos”);
        wait = new WebDriverWait(androidDriver, 20);
        wait.until(ExpectedConditions.visibilityOfElementLocated(taskListScreenTitleBar));

        clickOnButton(taskCommentsButton);

        softAssert.assertEquals(readScreenBarTitle(commentScreenTitleBar), “Comments”, “User Login failed and hence is not navigated to Dashboard. Screen Title do not match .. “);

        try {
        softAssert.assertAll();
        }catch (Error e) {
        verificationErrors.append(“\n ” + e.toString());
        testCaseResult = false;

        }
        Assert.assertTrue(testCaseResult, “\n Testcase Failed!, ” + “\n” + verificationErrors.toString());
        }

        private String readScreenBarTitle(By locator) {
        String text = getTextOfElement(locator);
        return text;
        }

        private void loginActions(String joinusername, String joinpassword) {
        // WebElement signInButton = null;
        enterTextInput(username, joinusername);
        enterTextInput(password, joinpassword);
        //androidDriver.hideKeyboard();

        // List screenButtons = (List) androidDriver.findElements(buttons);
        // System.out.println(“Number of buttons: ” + screenButtons.size());
        // for (WebElement currentButton : screenButtons) {
        // System.out.println(“button: “+currentButton.getAttribute(“content-desc”));
        // if(currentButton.getAttribute(“content-desc”).equalsIgnoreCase(“sign in”)) {
        // signInButton = currentButton;
        // }
        //
        // }
        androidDriver.context(“NATIVE_APP”);
        //androidDriver.switchTo().window(“WEBVIEW”);
        clickOnButton(signInButton);

        try {
        Thread.sleep(1000);
        } catch (InterruptedException e1) {
        e1.printStackTrace();
        }
        }

        @AfterClass(alwaysRun = true)
        public void tearDown() throws Exception {
        System.out.println(“In after class”);
        }

        protected void enterTextInput(By locator, String text) {
        WebElement txtBox = androidDriver.findElement(locator);
        if(txtBox.isDisplayed()){
        // txtBox.clear();
        txtBox.sendKeys(text);
        //androidDriver.hideKeyboard();
        try {
        Thread.sleep(1000);
        } catch (InterruptedException e1) {
        e1.printStackTrace();
        }

        }
        }

        protected void clickOnButton(By locator) {
        WebElement btn = androidDriver.findElement(locator);
        if(btn.isDisplayed())
        btn.click();

        else {
        throw new AssertionError(locator + ” button is not displayed”);
        }
        }

        protected void clickOnButton(WebElement btn) {
        if(btn.isDisplayed())
        btn.click();
        else {
        throw new AssertionError(” button is not displayed”);
        }
        }

        public String getTextOfElement(By locator) {
        WebElement element = null;
        String text = “”;
        //androidDriver.hideKeyboard();

        if ( isDisplayedOnPage(locator) ) {
        element = androidDriver.findElement(locator);
        text = element.getText();
        }
        return text;
        }

        public boolean isDisplayedOnPage(By locator){
        try {
        return androidDriver.findElement(locator).isDisplayed();

        } catch (NoSuchElementException e) {
        System.out.println(“Given element is not present on screen: ” + e.getMessage());
        return false;
        }
        catch (TimeoutException e) {
        System.out.println(“Timed out waiting for element visibility: ” + e.getMessage());
        return false;
        }
        }

        }

  5. Hi Karthik,

    Do you have any sample hybrid app apk file, with web view debugging enabled.
    Which I can use for practicing appium.

    Thanks,
    Naveen

Leave a Reply

Your email address will not be published. Required fields are marked *