Automating Native Mobile Apps with Appium Commands

 


4. Automating Native Mobile Apps with Appium

Now that we have set up the environment for Appium, we can move on to the actual testing process. In this section, we will create a basic Appium test that interacts with a mobile application.

4.1 Appium Commands for Interacting with Mobile Elements (Taps, Swipes, Inputs, etc.)

In this section of the tutorial, we will explore the commands and methods available in Appium for interacting with mobile elements such as taps, swipes, inputs, and more. These commands are essential for automating interactions with mobile apps during testing. We'll cover the commonly used commands and their usage in Appium using the Java client.

  1. Locating Mobile Elements:

i. Use the findElement(By locator) method to locate a single element based on a specified locator strategy (e.g., ID, XPath, class name).

ii. Use the findElements(By locator) method to locate multiple elements based on the same locator strategy.

Example:

java
MobileElement element = driver.findElement(By.id("com.example.app:id/button"));


2. Tapping on an Element:


Use the click() method to tap on a mobile element.

Example:

java
element.click();


3. Sending Text Input:


Use the sendKeys(CharSequence... keysToSend) method to send text input to a mobile element.

Example:

java
MobileElement inputField = driver.findElement(By.id("com.example.app:id/input_field")); inputField.sendKeys("Hello, Appium!");


4. Swiping:


Use the swipe(int startX, int startY, int endX, int endY, int duration) method to perform a swipe gesture from one point to another.

Example:

java
// Swipe from coordinates (startX, startY) to (endX, endY) over the duration of 1000 milliseconds driver.swipe(startX, startY, endX, endY, 1000);


5. Scrolling:


Use the scrollIntoView(MobileElement element) method to scroll to a specific element within a scrollable container.

Example:

java
MobileElement scrollableContainer = driver.findElement(By.id("com.example.app:id/scrollable_container")); MobileElement elementToScrollTo = driver.findElement(MobileBy.AndroidUIAutomator( "new UiScrollable(new UiSelector()).scrollIntoView(new UiSelector().text(\"Scrollable Item\"));")); scrollableContainer.scrollIntoView(elementToScrollTo);


6. Device Navigation:


Use the navigate() object to perform device navigation actions such as pressing the back button, home button, or locking the device.

Example:

java
driver.navigate().back(); // Press the Back button driver.navigate().home(); // Press the Home button driver.lockDevice(); // Lock the device // ...and more device navigation methods are available

By utilizing these commands and methods in your Appium test scripts, you can interact with mobile elements effectively. Appium provides a comprehensive set of functionality to simulate user interactions and gestures on mobile devices, enabling you to automate mobile app testing efficiently.


7. Long Press:

In Appium, to perform a long press or a long-press-and-move action on a mobile element, you can use the longPress(LongPressOptions) method. The LongPressOptions class allows you to configure the duration and other options for the long press action.

Here's an example of how to perform a long press on a mobile element using the Appium Java client:

java
import io.appium.java_client.TouchAction; import io.appium.java_client.touch.LongPressOptions; import io.appium.java_client.touch.offset.ElementOption; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; // Locate the mobile element to perform a long press on WebElement element = driver.findElement(By.id("com.example.app:id/button")); // Create an instance of TouchAction class TouchAction touchAction = new TouchAction(driver); // Configure the long press action options LongPressOptions longPressOptions = LongPressOptions.longPressOptions() .withElement(ElementOption.element(element)) .withDuration(ofSeconds(2)); // Set the duration for the long press (2 seconds in this example) // Perform the long press action touchAction.longPress(longPressOptions).release().perform();
In the above example, we first locate the mobile element on which we want to perform the long press action. Then, we create an instance of the TouchAction class and configure the LongPressOptions with the desired duration and the element on which the long press should be performed. Finally, we invoke the longPress method of TouchAction with the LongPressOptions and perform the long press action by calling perform().

4.2. Writing your first Appium Script

Step 1: Start Appium Server

Before you can start running tests with Appium, you need to start the Appium server. You can start the server using Appium Desktop or the command line.

To start the server using Appium Desktop, open the application and click the "Start Server" button. Appium will start the server and display the server log in the console.

To start the server using the command line, open a command prompt or terminal window and run the following command:

appium

This command will start the Appium server and display the server log in the console.


Step 2: Install Mobile Application

To automate testing for a mobile application, you need to have the application installed on your device or emulator. You can download the application from the app store or get it from the developer.


Step 3: Set Up Desired Capabilities

To run tests with Appium, you need to set up desired capabilities that define the device and application settings. Desired capabilities are a set of key-value pairs that specify the device, application, and other settings that you want to use for testing.

For example, to run tests for an Android application, you can set up desired capabilities as follows:

java
DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("platformName""Android"); capabilities.setCapability("deviceName""Android Emulator"); capabilities.setCapability("appPackage""com.example.android.myapplication"); capabilities.setCapability("appActivity""MainActivity"); capabilities.setCapability("automationName""UiAutomator2"); capabilities.setCapability("udid""emulator-5554");

In the code snippet above, we have set up desired capabilities for an Android emulator. We have specified the platform name as "Android", device name as "Android Emulator", the package name and activity name of the application, the automation name as "UiAutomator2", and the unique device identifier (UDID) of the emulator.

You can also set up desired capabilities for an iOS application as follows:

java
DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("platformName""iOS"); capabilities.setCapability("deviceName""iPhone 11"); capabilities.setCapability("platformVersion""14.5"); capabilities.setCapability("app""/path/to/app.app"); capabilities.setCapability("automationName""XCUITest"); capabilities.setCapability("udid""0123456789abcdef0123456789abcdef01234567");

In the code snippet above, we have set up desired capabilities for an iPhone device. We have specified the platform name as "iOS", device name as "iPhone 11", the platform version as "14.5", the path to the application file, the automation name as "XCUITest", and the UDID of the device.

Step 4: Write Test Code

Once you have set up desired capabilities, you can write test code to interact with the mobile application.

In the code snippet below, we will launch the application, enter a username and password, and click on the login button:

java
import io.appium.java_client.MobileElement; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.remote.MobileCapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import java.net.URL; import java.util.concurrent.TimeUnit; public class AppiumTest { public static void main(String[] args) throws Exception { // Set up desired capabilities DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android"); capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "emulator-5554"); capabilities.setCapability(MobileCapabilityType.APP, "/path/to/app.apk"); capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "UiAutomator2"); // Create Android driver AndroidDriver<MobileElement> driver = new AndroidDriver<MobileElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities); // Set implicit wait time driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); // Interact with mobile application MobileElement username = driver.findElementById("com.example.app:id/username"); username.sendKeys("testuser"); MobileElement password = driver.findElementById("com.example.app:id/password"); password.sendKeys("testpass"); MobileElement loginBtn = driver.findElementById("com.example.app:id/login"); loginBtn.click(); // Close application driver.quit(); } }

Example Code explanation:

Let's break down this code and see what each part does.

  1. Import Required Packages

First, we import the required packages for the test:

java
import io.appium.java_client.MobileElement; 
import io.appium.java_client.android.AndroidDriver; 
import io.appium.java_client.remote.MobileCapabilityType; 
import org.openqa.selenium.remote.DesiredCapabilities; 
import java.net.URL; 
import java.util.concurrent.TimeUnit;

Here, we import the MobileElement and AndroidDriver classes from the Appium Java client library, the DesiredCapabilities class from the Selenium Java library, and the URL class from the Java standard library. We also import the MobileCapabilityType enum from the Appium Java client library to set up desired capabilities.


2. Create Android Driver

Next, we create an Android driver using the desired capabilities:

java
// Create Android driver AndroidDriver<MobileElement> driver = new AndroidDriver<MobileElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);

Here, we create a new AndroidDriver object by passing the URL of the Appium server and the desired capabilities as parameters.

2.1. AndroidDriver<MobileElement>

The first part of this line of code declares a variable named "driver" of type AndroidDriver<MobileElement>. This means that the "driver" object is an instance of the AndroidDriver class that is capable of interacting with mobile elements.

2.2. new AndroidDriver<MobileElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities)

The second part of this line of code initializes the "driver" object. It creates a new instance of the AndroidDriver class and passes two arguments:

i. A URL object that represents the address of the Appium server. In this case, the address is "http://127.0.0.1:4723/wd/hub". This is the default address used by Appium server.

ii. A desired capabilities object that defines the properties and behavior of the session that the driver will create with the Appium server. This object is passed as an argument to the AndroidDriver constructor.

2.3. capabilities

The "capabilities" object is a desired capabilities object that is defined earlier in the code using the DesiredCapabilities class. It defines the properties and behavior of the session that the driver will create with the Appium server. In this case, it specifies the capabilities for an Android device, including the platform name, device name, and app package and activity.

Overall, this line of code initializes the "driver" object by creating a new instance of the AndroidDriver class and passing the Appium server URL and the desired capabilities object as arguments. Once the "driver" object is initialized, it can be used to interact with the mobile application.


  1. Set Implicit Wait Time

Next, we set an implicit wait time of 15 seconds:

java
// Set implicit wait time driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

Here, we set an implicit wait time of 15 seconds using the manage() method of the driver object and the timeouts() method. This will make the driver wait for up to 15 seconds for an element to appear before throwing an exception.


  1. Interact with Mobile Application

Next, we interact with the mobile application by finding elements and performing actions on them:

java
// Interact with mobile application MobileElement username = driver.findElementById("com.example.app:id/username"); username.sendKeys("testuser"); MobileElement password = driver.findElementById("com.example.app:id/password"); password.sendKeys("testpass"); MobileElement loginBtn = driver.findElementById("com.example.app:id/login"); loginBtn.click();

Here, we first find the "username" element by its ID using the findElementById() method of the driver object and assign it to a MobileElement object named "username". We then use the sendKeys() method to enter the text "testuser" into the "username" field.

Next, we find the "password" element by its ID using the findElementById() method of the driver object and assign it to a MobileElement object named "password". We then use the sendKeys() method to enter the text "testpass" into the "password" field.

Finally, we find the "login" button element by its ID using the findElementById() method of the driver object and assign it to a MobileElement object named "loginBtn". We then use the click() method to click the "login" button.

  1. Close Application

Finally, we close the application by quitting the driver:

java
// Close application driver.quit();

Here, we use the quit() method of the driver object to close the application and release all resources associated with it.

And that's it! This is a simple Appium test code for a mobile application that demonstrates how to set up desired capabilities, create an Android driver, interact with the application, and close it using the Appium Java client library. You can use this code as a starting point to write more complex tests for your mobile application.


4.3. Handling Alerts and Pop-ups in Appium:

Alerts and pop-ups are common elements in mobile applications that require special handling during test automation. Appium provides specific methods to interact with alerts and pop-ups, allowing you to accept, dismiss, or perform other actions based on their presence.

1. Accepting Alerts:
To accept an alert, you can use the accept() method. It clicks the "OK" or "Accept" button on the alert.

java
driver.switchTo().alert().accept();

2. Dismissing Alerts:

To dismiss an alert, you can use the dismiss() method. It clicks the "Cancel" or "Dismiss" button on the alert.

java
driver.switchTo().alert().dismiss();

3. Retrieving Alert Text:
To retrieve the text displayed on an alert, you can use the getText() method.

java
String alertText = driver.switchTo().alert().getText();

4. Entering Text in Alert Prompts:
In cases where an alert requires user input, such as a prompt, you can use the sendKeys() method to enter text into the input field of the alert.

java
Alert alert = driver.switchTo().alert(); alert.sendKeys("Your text here"); alert.accept();

5. Handling Expected Alerts:
If you expect an alert to appear during the execution of your test, you can use the WebDriverWait class in combination with the ExpectedConditions class to wait for the alert to be present and then perform the desired action.

java
WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.alertIsPresent()); driver.switchTo().alert().accept();

6. Handling Unexpected Alerts:
If an unexpected alert appears during the execution of your test, you can use a try-catch block to handle it. Catch the NoAlertPresentException and handle the alert accordingly.

java
try { driver.switchTo().alert().accept(); } catch (NoAlertPresentException e) { // Alert not present, continue with the test }

By using these methods, you can handle alerts and pop-ups effectively in your Appium test scripts. It enables you to interact with these elements based on the specific actions required, allowing you to automate scenarios involving alerts and pop-ups in mobile applications.


Author
Vaneesh Behl
Passionately writing and working in Tech Space for more than a decade.

Comments

Popular posts from this blog

Top 10 Highly Paid Indian CEOs in the USA

What Role Graphic Design Services Play in Marketing

Python Behave Tutorial: A Comprehensive Guide to Behavior-Driven Development (BDD)

Testing a Web Page/Website: Best Practices for Quality Assurance and Improved User Experience

Mastering Selenium Practice: Automating Web Tables with Demo Examples

14 Best Selenium Practice Exercises for Automation Practice

Real-World Examples and Demo Scripts in Selenium Python Automation

Complete Guide to Software Testing Levels: From Unit to End-to-End Testing

How to Solve Easily the Reader-Writer Locks in Golang

Top 11 Interview Blunders That Can Cost You the Job: Expert Tips to Avoid Them