Showing posts with label Appium. Show all posts
Showing posts with label Appium. Show all posts

Monday 4 June 2018

Easiest Way to Start Appium Server with Java Code

When we are building an automation framework it is very important to perform end to end automation including starting and stopping appium server. keeping that in mind in this post I will be sharing simplest and quickest way to install appium server and start & stop appium server using simple java code.
This is very simple and easy way to start appium server programmatically using java code. In our previous tutorial we have seen how to start appium server using java code with this   AppiumDriverLocalService class. But in this tutorial we will see very simple and quick way of installing appium server and starting it using simple java code.


Step 1 > Install Node Js from  HERE
 
Step 2 > Open Node Js Command Prompt as shown below.

Step 3 > Execute command npm install -g appium
 
Step 4 > Verify Appium is Installed Successfully by executing command  appium -v
 
Step 5 > Start appium server using command appium -a 127.0.0.1 -p 4723
 
Step 6 > Do CTRL + C to stop ther server

Below is the Java Code to Start and Stop Appium Server Programaticall. In the code we
are executing the command using java to start and stop the server.
Do try this out and post your feedback, Suggestion and questions in comment section 
below.



import java.io.IOException;

/**
 * Appium Manager - this class contains method to start and stops appium server  
 */
public class AppiumManager {

 public void startServer() {
  Runtime runtime = Runtime.getRuntime();
  try {
   runtime.exec("cmd.exe /c start cmd.exe /k \"appium -a 127.0.0.1 -p 4725 --session-override -dc \"{\"\"noReset\"\": \"\"false\"\"}\"\"");
   Thread.sleep(10000);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public void stopServer() {
  Runtime runtime = Runtime.getRuntime();
  try {
   runtime.exec("taskkill /F /IM node.exe");
   runtime.exec("taskkill /F /IM cmd.exe");
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

Saturday 16 December 2017

How to Test Toast Messages using Appium?

We can not directly used Appium Client API to test toast messages. So here we will import Tess4j jar in our project and their APIs to Read Toast Messages From our Screenshot . Once we have the text on the screen we can verify the toast message text in our Appium Test Case via various assertions .

For more Details Refer to this Video -


Let us see the code to take screen shot and then read the text from screen shot.



package com.appium.xample;



import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import net.sourceforge.tess4j.util.LoadLibs;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

import io.appium.java_client.android.AndroidDriver;

public class ReadToastMessage {
 
  static String scrShotDir = "screenshots";
  File scrFile;
  static File scrShotDirPath = new java.io.File("./"+ scrShotDir+ "//");
  String destFile;
  static AndroidDriver driver = null;
 
 public String readToastMessage() throws TesseractException {
  String imgName = takeScreenShot();
  String result = null;
  File imageFile = new File(scrShotDirPath, imgName);
  System.out.println("Image name is :" + imageFile.toString());
  ITesseract instance = new Tesseract();

  File tessDataFolder = LoadLibs.extractTessResources("tessdata"); // Extracts
                   // Tessdata
                   // folder
                   // from
                   // referenced
                   // tess4j
                   // jar
                   // for
                   // language
                   // support
  instance.setDatapath(tessDataFolder.getAbsolutePath()); // sets tessData
                // path

  result = instance.doOCR(imageFile);
  System.out.println(result);
  return result;
 }

 /**
  * Takes screenshot of active screen
  * 
  * @return ImageFileName
  */
 public String takeScreenShot() {
  File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); 
  
  SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy__hh_mm_ssaa");
  new File(scrShotDir).mkdirs(); // Create folder under project with name
          // "screenshots" if doesn't exist
  destFile = dateFormat.format(new Date()) + ".png"; // Set file name
               // using current
               // date time.
  try {
   FileUtils.copyFile(scrFile, new File(scrShotDir + "/" + destFile)); // Copy
                    // paste
                    // file
                    // at
                    // destination
                    // folder
                    // location
  } catch (IOException e) {
   System.out.println("Image not transfered to screenshot folder");
   e.printStackTrace();
  }
  return destFile;
 }
}

Saturday 7 October 2017

Swipe Right,Left,Up & Down using Appium

This is very useful tutorial for those who are learning appium as swiping and scrolling is commonly used for almost all mobile apps. So learning to automate it using Appium is going to help you in writing test code.Below is the code where I have written different functions for swiping from top to bottom, from bottom to top, from left to right, from right to left using Appium. We can all these methods in our test cases to perform required actions. plus I have created a video tutorial with detailed explanation.



/**
  /* Method to swipe screen from Bottom to Top (Vertical) Get the size of
  * screen. Find swipe start and end point from screen's width and height.
  * Find starty point which is at bottom side of screen. Find endy point
  * which is at top side of screen. Find horizontal point where you wants to
  * swipe. It is in middle of screen width.
  * Time duration should be in milliseconds
  */

 public void bottomTopswipe(int timeduration) {

  
  size = driver.manage().window().getSize();
  System.out.println(size);
  starty = (int) (size.height * 0.50);
  endy = (int) (size.height * 0.20);
  startx = size.width / 2;
  System.out.println("Start swipe operation");
  driver.swipe(startx, starty, startx, endy, timeduration);

 }

 /**
  * 
  * Method to swipe screen from Top to Bottom (Vertical) Get the size of
  * screen. Find swipe start and end point from screen's width and height.
  * Find starty point which is at bottom side of screen. Find endy point
  * which is at top side of screen. Find horizontal point where you wants to
  * swipe. It is in middle of screen width. 
         * Time duration should be in milliseconds
   */

 public void topBottomswipe(int timeduration) {

  
  size = driver.manage().window().getSize();
  System.out.println(size);
  starty = (int) (size.height * 0.50);
  endy = (int) (size.height * 0.20);
  startx = size.width / 2;
  System.out.println("Start swipe operation");
  driver.swipe(startx, endy, startx, starty, timeduration);

 }

 /**
  * 
  * Method to swipe screen from right to left (Horizontal) duration should be
  * in milliseconds Get the size of screen. Find swipe start and end point
  * from screen's width and height. Find startx point which is at right side
  * of screen. Find endx point which is at left side of screen. Find vertical
  * point where you wants to swipe. It is in middle of screen height. 
         * Time duration should be in milliseconds
   */

 public void rightLeftSwipe(int timeduration) {

  size = driver.manage().window().getSize();
  System.out.println(size);
  startx = (int) (size.width * 0.70);
  endx = (int) (size.width * 0.30);
  starty = size.height / 2;
  System.out.println("Start swipe operation");
  driver.swipe(startx, starty, endx, starty, timeduration);

 }

 /**
  * 
  * Method to swipe screen from left to right (Horizontal) duration should be
  * in milliseconds Get the size of screen. Find swipe start and end point
  * from screen's width and height. Find startx point which is at right side
  * of screen. Find endx point which is at left side of screen. Find vertical
  * point where you wants to swipe. It is in middle of screen height. 
         * Time duration should be in milliseconds
      */

 public void leftRightSwipe(int timeduration) {
  // duration should be in milliseconds
  size = driver.manage().window().getSize();
  System.out.println(size);
  startx = (int) (size.width * 0.70);
  endx = (int) (size.width * 0.30);
  starty = size.height / 2;
  System.out.println("Start swipe operation");
  driver.swipe(endx, starty, startx, starty, timeduration);

 }

Friday 2 June 2017

Page Object Model ( POM ) in Appium

Starting an UI Automation in Appium is not a tough task. You just need to locate elements, perform actions on it.
A small Appium test script maintenance looks easy,but ut with time test suite will grow into multiple test scripts. As you add more and more lines to your code, things become tough to maintain.The chief problem with script maintenance is that if 10 different scripts are using the same mobile element, with any change in that element, you need to change all 10 scripts. This is time consuming and error prone.
A better approach to test scripts maintenance is to create a separate class file which would find mobile elements, fill them or verify them which can be reused in all the scripts using that element. In future, if there is a change in the web element, we need to make the change in just 1 class file and not 10 different test scripts.This approach is called Page Object Model(POM). It helps make the code more readable, maintainable, and reusable.

Video Tutorial -

 

What is POM?


1. Page Object Model is a design pattern.
2. Under this model, for each mobile app screen , there should be corresponding page class.
3. This Page class will find the MobileElements of that mobile screen page and also contains Page methods which perform operations on those MobileElements .
4. Name of these methods should be given as per the task they are performing, i.e., if a loader is waiting for the login page to appear, POM method name can be waitForLoginScreenDisplay().

Advantages of POM


1.Page Object Model defines that operations and test scenario flows in the UI should be separated from verification. This concept makes code cleaner and easier to understand.
2.The Second benefit is the object repository is kept independent of test cases, so we can use the same object repository for a different purpose and with different tools. For example, we can integrate POM with TestNG/JUnit for functional Testing and at the same time with JBehave/Cucumber for acceptance testing.
3.Code becomes reusable and optimized .


How to Use POM?



Core Class for Desired Capabilities related setup -
 This class we can use to write core setup related code which is common for executing each Appium test case.


package com.example.anuja.appiumapplication;

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

import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;

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

/**
 * Created by Anuja on 6/2/2017.
 */

public class BaseSetup {

        private DesiredCapabilities capabilities = new DesiredCapabilities();
        private static AndroidDriver androidDriver = null;

        private String appiumPort;
        private String serverIp;

        @BeforeClass
        public void setup(){
            initDriver();
        }

        public AndroidDriver getDriver() {
            return androidDriver;
        }

        private void initDriver(){
            System.out.println("Inside initDriver method");

            DesiredCapabilities cap = new DesiredCapabilities();
            cap.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
            cap.setCapability(MobileCapabilityType.DEVICE_NAME, "Android device");
            cap.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, "4000");
            cap.setCapability(MobileCapabilityType.APP, "c://apks//listviewsample.apk");
            cap.setCapability("noReset", true);
            String serverUrl = "http://" + serverIp + ":" + appiumPort + "/wd/hub";


            try
            {
                System.out.println("Argument to driver object : " + serverUrl);
                androidDriver = new AndroidDriver(new URL(serverUrl), capabilities);

            }
            catch (NullPointerException | MalformedURLException ex) {
                throw new RuntimeException("appium driver could not be initialised for device ");
            }
            System.out.println("Driver in initdriver is : "+androidDriver);

        }

        @AfterClass
        public void tearDown(){
            androidDriver.quit();
        }

    }
Driver class -
This class to instantiate driver object.


import io.appium.java_client.android.AndroidDriver;

/**
 * Created by Anuja on 6/2/2017.
 */

public class Driver extends BaseSetup{

    protected AndroidDriver driver;

    public Driver() {
        this.driver = super.getDriver();
    }
}
Page Class for Login Page -
This is how our page class looks.

import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.testng.Assert;




/**
 * Created by Anuja on 5/17/2017.
 */

public class LoginPage extends Driver{

    PageObjects loginPage;

    String userName = "";
    String passWord = "";

    public LoginPage() {
        super();
        loginPage = new PageObjects();
        PageFactory.initElements(driver, loginPage);
    }

    public boolean validateLoginpage(){
        boolean elements = false;
        if(loginPage.userNameFld.isDisplayed()){
            if(loginPage.passwordField.isDisplayed()){
                if(loginPage.checkBox.isDisplayed()){
                    if(loginPage.loginBtn.isDisplayed()){
                        elements = true;
                    }
                }
            }
        }
        else{
            elements = false;
        }
        return elements;


    }

    public boolean testLoginWithoutCredentials() {
        boolean loginStatus = false;
        loginPage.loginBtn.click();
        if (loginPage.inputError.getText().equalsIgnoreCase("Username is mandatory")) {
            loginStatus = true;
        }
        loginPage.userNameFld.sendKeys(userName);
        loginPage.loginBtn.click();
        if (loginPage.inputError.getText().equalsIgnoreCase("Password is mandatory")) {
            loginStatus = true;
        }
        return loginStatus;

    }



    class PageObjects {

        @CacheLookup
        @FindBy(id = "et_username")
        public WebElement userNameFld;

        @CacheLookup
        @FindBy(id = "et_password")
        public WebElement passwordField;

        @CacheLookup
        @FindBy(id = "btnSignin")
        public WebElement loginBtn;

        @CacheLookup
        @FindBy(name = "Invalid ID or password.")
        public WebElement inputError;

        @CacheLookup
        @FindBy(id = "checkBox")
        public WebElement checkBox;


    }
}

Test Case class for writing login page test cases - 
This is how our test case is going to look.

import org.junit.Test;

/**
 * Created by Anuja on 5/17/2017.
 */

public class LoginTests {

    @Test
    public void testLogin()
    {
        LoginPage loginPage = new LoginPage();
        if(loginPage.validateLoginpage() == true){
            loginPage.testLoginWithoutCredentials();
            System.out.println("pass");
        }
        else{
            System.out.println("Validation failed");
        }

    }
}
I hope you like this post. do share your queries and feedback in comment section below and please follow me on social media for latest post updates.




Thursday 5 January 2017

How to Handle App Permissions popup in Appium Test

We have faced this issue of Marshmallow Android Devices that apps shows permission popups asking for user permission to allow or deny. To handle this inside our automated test case is required. So this post will explain how we can handle this with simple code.
Consider we have an mobile app which asks for all required permission at the time of launch and we need to click on allow button each time it displays the App permission popup.


Check the below Test Case Example where we are calling allowAppPermission() method to click on each app permission popup. Let us see how the method internally works. In this method we have added a while loop until we get the allow app permission button . To locate the allow button we have used MobileBy api which is provided by lastest Appium Java Client.

Video Tutorial -

 




import java.net.MalformedURLException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;



public class WaitTests {

 WebDriver driver;

 @Before
 public void setUp() throws MalformedURLException {
  
  DesiredCapabilities capabilities = new DesiredCapabilities();
  capabilities.setCapability("deviceName", "XT1562");
  capabilities.setCapability(CapabilityType.BROWSER_NAME, "Android");
  capabilities.setCapability(CapabilityType.VERSION, "6.0.1");
  capabilities.setCapability("platformName", "Android");
  driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
  driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
  
  
 }

 @Test
 public void testFirst() {
  
   alllowAppPermission();
   driver.findElement(By.name("Login")).click();
   driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); 
}

@After
 public void End() {
  driver.quit();
 }
public void allowAppPermission(){
 while (driver.findElements(MobileBy.xpath("//*[@class='android.widget.Button'][2]")).size()>0) 

 {  driver.findElement(MobileBy.xpath("//*[@class='android.widget.Button'][2]")).click();
 }
}
 

}

I hope you find this useful. Please share your feedback in comments section below and follow me on social media for latest post updates.

Tuesday 3 January 2017

Jenkins For Appium and Maven Project

Video Tutorial -

Introduction of Jenkins

Jenkins is the leading open-source continuous integration tool developed by Hudson lab. It is cross-platform and can be used on Windows, Linux, Mac OS and Solaris environments. Jenkins is written in Java Programming language.Jenkins is a powerful application that allows continuous integration and continuous delivery of projects, regardless of the platform you are working on. You can integrate Jenkins with a number of testing and deployment technologies. In this tutorial, we will learn Jenkins with Maven project

Important Features of Jenkins

1. Jenkins generates the list of all changes done in repositories like SVN,Github.
2.Jenkins provides direct links to the latest build or failed build that can be used for easy communication.
3. Jenkins is easy to install either using direct installation file (exe).
4. Jenkins can be configured to email the content of the status of the build.
5. To configure various tasks on Jenkins is easy.
6. Jenkins can be configured to run the automation test build on TestNG after each build.
7. Jenkins can be configured to distribute the build on multiple machines.
8. 3rd party plugin can be configured in Jenkins to use features and additional functionality.

Why Jenkins and Appium?

1. Running Appium tests in Jenkins allows you to run your tests every time your software changes.
2. Jenkins can schedule your tests to run at specific time which is good for regression test execution for each build.
3. You can save the execution history reports and Test result reports.
4. Jenkins supports Maven for building and testing a project in continuous integration.

Jenkins Installation


1. First of all download Jenkins from HERE.
2. Install Jenkins.

Install Jenkins

3. Once it is installed open  http://localhost:8080/ url in browser.

Install Jenkins

4. Then navigate to the path and enter the password and click on continue

Install Jenkins

5. Click on Manage Jenkins



6. Click on Manage Plugins

7. Search for "Maven Integration Plugin" and select install without restart option.

8. After Maven Installation is successful we can get the Maven project while adding New Item

9. Go to New Item -> Enter The Name -> Select Maven Project -> Click OK

Jenikins Appium Maven


10. Scroll down to build and you will find option that Jenkins want to know where your maven is installed. then click on the tool configuration.
Jenikins Appium Maven

11. Then add your jdk path and maven path.

Jenikins Appium Maven
12. In the build Root POM give your project pom.xml path.
Jenikins Appium Maven

13. Save the changes and click on Build Now.

Jenikins Appium Maven 
14. Once the Build is executed you can check the build history.