Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      May 16, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      May 16, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      May 16, 2025

      How To Prevent WordPress SQL Injection Attacks

      May 16, 2025

      Microsoft has closed its “Experience Center” store in Sydney, Australia — as it ramps up a continued digital growth campaign

      May 16, 2025

      Bing Search APIs to be “decommissioned completely” as Microsoft urges developers to use its Azure agentic AI alternative

      May 16, 2025

      Microsoft might kill the Surface Laptop Studio as production is quietly halted

      May 16, 2025

      Minecraft licensing robbed us of this controversial NFL schedule release video

      May 16, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      The power of generators

      May 16, 2025
      Recent

      The power of generators

      May 16, 2025

      Simplify Factory Associations with Laravel’s UseFactory Attribute

      May 16, 2025

      This Week in Laravel: React Native, PhpStorm Junie, and more

      May 16, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Microsoft has closed its “Experience Center” store in Sydney, Australia — as it ramps up a continued digital growth campaign

      May 16, 2025
      Recent

      Microsoft has closed its “Experience Center” store in Sydney, Australia — as it ramps up a continued digital growth campaign

      May 16, 2025

      Bing Search APIs to be “decommissioned completely” as Microsoft urges developers to use its Azure agentic AI alternative

      May 16, 2025

      Microsoft might kill the Surface Laptop Studio as production is quietly halted

      May 16, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Automating Native Mobile Apps with Appium Commands

    Automating Native Mobile Apps with Appium Commands

    April 21, 2024

     

    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.

    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.

    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.


    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.


    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.

    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.

    Source: Read More

    Hostinger
    Facebook Twitter Reddit Email Copy Link
    Previous ArticleTop 10 Highly Paid Indian CEOs in the USA
    Next Article Applications of Artificial Intelligence in Healthcare

    Related Posts

    Security

    Nmap 7.96 Launches with Lightning-Fast DNS and 612 Scripts

    May 17, 2025
    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-40906 – MongoDB BSON Serialization BSON::XS Multiple Vulnerabilities

    May 17, 2025
    Leave A Reply Cancel Reply

    Hostinger

    Continue Reading

    Google AI Introduces Proofread: A Novel Gboard Feature Enabling Seamless Sentence-Level And Paragraph-Level Corrections With A Single Tap

    Development
    Using generative AI and Amazon Bedrock to generate SPARQL queries to discover protein functional information with UniProtKB and Amazon Neptune

    Using generative AI and Amazon Bedrock to generate SPARQL queries to discover protein functional information with UniProtKB and Amazon Neptune

    Databases

    CVE-2025-4757 – PHPGurukul Beauty Parlour Management System SQL Injection Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    PINEAPPLE and FLUXROOT Hacker Groups Abuse Google Cloud for Credential Phishing

    Development

    Highlights

    How to Fix the UCMUCSI_FAILURE Error on Windows

    December 20, 2024

    The UCMUCSI_FAILURE error, also known as bug check 0x1D8, indicates that the USB Type-C Connector…

    Pixel 9a details leak – how its specs compare to my Pixel 9 Pro

    February 19, 2025

    Russia Spreading Deepfakes and Misinformation on Kursk Offensive, Says Ukraine

    August 14, 2024

    Mirai Botnet Launches Record 5.6 Tbps DDoS Attack with 13,000+ IoT Devices

    January 22, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.