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 AppiumDriverLocalServiceclass. But in this tutorial we will see very simple and quick way of installing appium server and starting it using simple java code.
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;importnet.sourceforge.tess4j.ITesseract;importnet.sourceforge.tess4j.Tesseract;importnet.sourceforge.tess4j.TesseractException;importnet.sourceforge.tess4j.util.LoadLibs;importjava.io.File;importjava.io.IOException;importjava.text.SimpleDateFormat;importjava.util.Date;importorg.apache.commons.io.FileUtils;importorg.apache.commons.io.FilenameUtils;importorg.openqa.selenium.OutputType;importorg.openqa.selenium.TakesScreenshot;importio.appium.java_client.android.AndroidDriver;publicclassReadToastMessage{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");newFile(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;}}
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 */publicvoidbottomTopswipe(inttimeduration){
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
*/publicvoidtopBottomswipe(inttimeduration){
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
*/publicvoidrightLeftSwipe(inttimeduration){
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
*/publicvoidleftRightSwipe(inttimeduration){// 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);}
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.
packagecom.example.anuja.appiumapplication;importjava.io.File;importjava.net.MalformedURLException;importjava.net.URL;importjava.util.Properties;importorg.openqa.selenium.remote.CapabilityType;importorg.openqa.selenium.remote.DesiredCapabilities;importorg.testng.annotations.AfterClass;importorg.testng.annotations.BeforeClass;importio.appium.java_client.AppiumDriver;importio.appium.java_client.android.AndroidDriver;importio.appium.java_client.remote.MobileCapabilityType;/** * Created by Anuja on 6/2/2017. */publicclassBaseSetup{privateDesiredCapabilitiescapabilities=newDesiredCapabilities();privatestaticAndroidDriverandroidDriver=null;privateStringappiumPort;privateStringserverIp;@BeforeClasspublicvoidsetup(){initDriver();}publicAndroidDrivergetDriver(){returnandroidDriver;}privatevoidinitDriver(){System.out.println("Inside initDriver method");DesiredCapabilitiescap=newDesiredCapabilities();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);StringserverUrl="http://"+serverIp+":"+appiumPort+"/wd/hub";try{System.out.println("Argument to driver object : "+serverUrl);androidDriver=newAndroidDriver(newURL(serverUrl),capabilities);}catch(NullPointerException|MalformedURLExceptionex){thrownewRuntimeException("appium driver could not be initialised for device ");}System.out.println("Driver in initdriver is : "+androidDriver);}@AfterClasspublicvoidtearDown(){androidDriver.quit();}}
Driver class -
This class to instantiate driver object.
importio.appium.java_client.android.AndroidDriver;/** * Created by Anuja on 6/2/2017. */publicclassDriverextendsBaseSetup{protectedAndroidDriverdriver;publicDriver(){this.driver=super.getDriver();}}
Page Class for Login Page -
This is how our page class looks.
importorg.openqa.selenium.WebElement;importorg.openqa.selenium.support.CacheLookup;importorg.openqa.selenium.support.FindBy;importorg.openqa.selenium.support.PageFactory;importorg.testng.Assert;/** * Created by Anuja on 5/17/2017. */publicclassLoginPageextendsDriver{PageObjectsloginPage;StringuserName="";StringpassWord="";publicLoginPage(){super();loginPage=newPageObjects();PageFactory.initElements(driver,loginPage);}publicbooleanvalidateLoginpage(){booleanelements=false;if(loginPage.userNameFld.isDisplayed()){if(loginPage.passwordField.isDisplayed()){if(loginPage.checkBox.isDisplayed()){if(loginPage.loginBtn.isDisplayed()){elements=true;}}}}else{elements=false;}returnelements;}publicbooleantestLoginWithoutCredentials(){booleanloginStatus=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;}returnloginStatus;}classPageObjects{@CacheLookup@FindBy(id="et_username")publicWebElementuserNameFld;@CacheLookup@FindBy(id="et_password")publicWebElementpasswordField;@CacheLookup@FindBy(id="btnSignin")publicWebElementloginBtn;@CacheLookup@FindBy(name="Invalid ID or password.")publicWebElementinputError;@CacheLookup@FindBy(id="checkBox")publicWebElementcheckBox;}}
Test Case class for writing login page test cases -
This is how our test case is going to look.
importorg.junit.Test;/** * Created by Anuja on 5/17/2017. */publicclassLoginTests{@TestpublicvoidtestLogin(){LoginPageloginPage=newLoginPage();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.
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.
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.
3. Once it is installed open http://localhost:8080/ url in browser.
4. Then navigate to the path and enter the password and click on continue
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
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.
11. Then add your jdk path and maven path.
12. In the build Root POM give your project pom.xml path.
13. Save the changes and click on Build Now.
14. Once the Build is executed you can check the build history.