The Ultimate Guide to Appium Testing with Examples
Tags: appium
Published: 2023-09-04 07:21:05

Testing is essential to ensuring that mobile applications are successful and effective in today's quickly expanding world of mobile applications. The well-known open-source Appium mobile automation framework runs web, hybrid, and native apps on a range of mobile devices. This in-depth guide explains Appium's core capabilities and provides practical examples to demonstrate how to use it to run tests.

##What is Appium?

Appium is a well-known open-source cross-platform tool that assists developers and testers in creating automated tests for mobile, hybrid, and native apps. 

Using Appium's client integration library, testers can create tests in their preferred languages such as Java, Python, Ruby, JavaScript, or C#.

Cross-platform support is one of Appium's core features; it enables developers to write tests only once and run them unchanged across a variety of systems, doing away with the need to write separate tests for each platform. This provides consistent measurements across many devices and operations while saving time and effort.

 Appium supports both iOS and Android platforms, so testers or developers may create tests that work well on a variety of hardware and emulators/simulators. Scripts should no longer require separate platform testing.

In order to locate content in the UI of the application, Appium offers a variety of locating methods including ID, XPath, class name, and login ID. Additionally, Appium offers a collection of APIs and protocols for engaging with users of mobile apps, enabling testers to mimic user behaviors including button clicks, text entry, scrolling, and property validation.



## Appium can be used for:

Appium can be used for a wide range of purposes, such as

Automating tests for mobile apps
Regression testing
End-to-end mobile automation
GUI testing
Performance testing
Automating acceptance tests



## What are the prerequisites to use Appium?

The prerequisites that are used in Appium are listed below: 
Web driver language binding library
JS
JDK
APK App Info on Google Play
Selenium server jar
Eclipse IDE
Android SDK
TestNG

## Why to use Appium? 
Appium became an important framework for automated mobile testing that provided all the features developers and testers needed to get things done Appium includes, but is not limited to, the following key features. 

**Open source**: Appium is an open-source tool that offers unlimited usability and provides a variety of free features. 

**Multilingual support**: This is a handy tool for developers because of the many programming languages ​​supported by Appium; Including Java, Python, Ruby, and JavaScript.

**Easy to use**: Appium is easy to learn and use, which means that developers and testers with no prior experience with mobile automated processes can adapt quickly.

**Acceleration**: Appium enables users to quickly run tests on multiple devices, making it easier to test multiple devices in a short period of time.

**Low hardware requirements**: Hardware requirements are low in Appium as all testing is done on the platform's emulator. 

**Easy Setup**: Appium is very easy to set up, so it is a good option for first-time users.

**Support for cross-platform development**: Appium offers support for both iOS and Android platforms, so it’s a good option in this regard.

**Provides multiple automation frameworks**: Appium is a customizable tool for developers, enabling them to work with different automation frameworks such as TestNG, JUnit, and NUnit.

## Appium Architecture

**- Client/Server Architecture**
Appium is fundamentally a web server that makes a REST API accessible. It takes connections from clients, listens for commands, carries out those actions on mobile devices, and then responds with an HTTP response that summarises the results of the command execution. Because our architecture is client/server, we can write our test code in any language with a HTTP client API, although it is more practical to utilize one of the Appium client libraries. On a different machine than the one where our testing is done, we can run the server.
Session

In order to automate sessions, the session context is always used. Although clients initially establish sessions with servers using techniques specific to each library, all clients eventually send a POST /session request to the server along with a JSON object known as the "desired capabilities" object. The automation session will now start, and the server will respond with a session ID that may be used to send further commands.


**- Desired Capabilities**

To inform the Appium server of the type of automation session we want to construct, we supply the server with a map or hash of desired capabilities. Numerous capabilities can also alter a server's behavior during automation. 

**- Appium Server**

Appium refers to a server built with Node.js. It can be created and installed from source code, or it can be installed directly through NPM.

**- Appium Clients**

In Java, Ruby, Python, PHP, JavaScript, and C#, there exist client libraries that support the changes to the WebDriver protocol made by Appium. When using Appium, you should utilize these client libraries rather than your usual WebDriver client.

##  Set up for Appium testing on Android Device

You must set up your testing environment and do the following steps in order to execute an Appium test on an Android device:

1.  Setup the prerequisites: 

You must install the Java Development Kit (JDK) on your computer. 
Before installing the Android SDK, ensure that the Android Debug Bridge (ADB) is installed. 
Installing Node.js is required: Visit node.js Download and install the installation that is appropriate for your operating system from the Node.js website (https://nodejs.org).
Install Appium: Use the npm (Node Package Manager) command line to install Appium globally:

```
npm install -g appium

```

To install Appium client: Run the following command: 

```
npm install -g appium-doctor.
```

2. Setting up a workspace for the creation of Android apps: 

Install Android SDK: Download Android SDK for your respecting operating system from the official Android Developer website (https://developer.android.com/studio). 
Creating the environment variable “ANDROID_HOME” on the installation path for the Android SDK by setting a variable in the environment.
Apart from this, “platform-tools” and “tools” directories should now be included in the “PATH” environment variable.


3. Setup your Android device:

Activate developer build settings: On your Android handset, navigate to Settings > About Phone, and then click on “Build number ” several times to enable the developer option. In the developer options, USB debugging can be enabled. 


4. Connect the device to your computer with a USB cable. 


5. Verify your device's connectivity:

 " adb devices " should be entered in a command window or terminal. Device IDs and linked devices should be visible.


6.  Begin utilizing the Appium server:

Enter the following command at a terminal or command prompt: 

```
appium
```
  

The Appium server will launch at port 4723 and provide a map of where the application is located.


7. Craft an Appium test script:
Using the tools offered by Appium, you may develop Appium tests in any programming language, including Java, Python, and JavaScript. Choose a programming language, and then ascertain all prerequisites.

Here's a sample code snippet using Java and the Appium Java client library to perform basic Appium testing on an Android device:

```
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.net.MalformedURLException;
import java.net.URL;


public class AppiumTest {


    public static void main(String[] args) {
        // Set the desired capabilities
        DesiredCapabilities caps = new DesiredCapabilities();
        caps.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
        caps.setCapability(MobileCapabilityType.DEVICE_NAME,”Google pixel 7A” );
        caps.setCapability(MobileCapabilityType.APP_PACKAGE, "com.example.app");
        caps.setCapability(MobileCapabilityType.APP_ACTIVITY, "com.example.app.MainActivity");
        caps.setCapability(MobileCapabilityType.AUTOMATION_NAME, "UiAutomator2");
        caps.setCapability(MobileCapabilityType.NO_RESET, true);


        // Initialize the Android driver
        AndroidDriver<MobileElement> driver = null;
        try {
            driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), caps);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }


        // Perform actions on the app
        MobileElement element = driver.findElement(By.id("element_id"));
        element.click();
        element.sendKeys("Hello World");


        // Assert element text
        assert element.getText().equals("Expected Text");


        // Take a screenshot
        File screenshotFile =   driver.getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(screenshotFile, new File("path/to/save/screenshot.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }


        // Quit the driver
        driver.quit();
    }
  }
```

In the test script above, make sure to replace "DEVICE_NAME" "APP_PACKAGE," and "APP_ACTIVITY" with the names of your associated devices.

8. Identify the precise capabilities required:

In order to identify the Android devices and apps that will be tested, details such as PlatformName, PlatformVersion, deviceName, or app capabilities must be specified. Programmes like Adobe ADB or APK Analyzer can be used to find an app's package name and function name.



9. Carrying out Appium tests:
 
Remembering to save the tests with the proper name and extension (AppiumTest.java) is essential. 

Using the terminal or command prompt, locate the test script, and then execute it from the test directory.

Logs and debug information are accessible on the Appium server console when the test is finished. It is also possible to record and save test results and transcripts in a file for later use.


Appium will communicate with the Appium Server interacting with the Android device to automate the testing process based on the commands in the test script. To interact with the
Appium server and write your tests in your favorite programming language, be sure to update the required functionality in your tests according to your Android device and the application under test (such as the Appium Java client).

## set up for Appium Testing on IOS device

To conduct Appium tests on an iOS device, you must follow these general procedures:

1. Installment requirements

Install Node.js: Go to the Node.js website at (https:///nodejs.org) and get the installation for your particular operating system there.

Configure Appium: At a terminal or command prompt, type the following command:

```
npm install -g appium

```
2. Set up iOS development environment 

Install Xcode: Utilise the Mac App Store to install Xcode. The simulator and other tools required for iOS programming are present.
Installation of the Xcode Command Line Tools: Open a terminal and enter the following command:

```
xcode-select --install

```

WebDriverAgent must be installed in order for Appium to automate iOS applications. 

3. Connect your iOS gadget:

Utilise a USB cable to link your iOS device to your Mac. Check to see if your device is shown in the Xcode device list and is recognized by your Mac.

Go to Settings > Developers> Enable UI Automation on your iOS device.


4. Launch the server for Appium:

Enter the following command at a terminal or command prompt:

```
appium
```

You might notice a record of the server in activity as soon as the Appium server starts up.


5. Create an Appium test script

You can create Appium tests in Java, Python, or JavaScript using your preferred programming language.

Here is an example of a code snippet that runs basic Appium testing on an IOS device using Java and the Appium Java client library:

```
import io.appium.java_client.MobileElement;
import io.appium.java_client.ios.IOSDriver;
import io.appium.java_client.remote.MobileCapabilityType;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.net.MalformedURLException;
import java.net.URL;


public class AppiumTest {


    public static void main(String[] args) {
        // Set the desired capabilities
        DesiredCapabilities caps = new DesiredCapabilities();
        caps.setCapability(MobileCapabilityType.PLATFORM_NAME, "iOS");
        caps.setCapability(MobileCapabilityType.DEVICE_NAME, "iphone XR");
        caps.setCapability(MobileCapabilityType.UDID, "device_udid");
        caps.setCapability(MobileCapabilityType.APP, "path/to/app");
        caps.setCapability(MobileCapabilityType.AUTOMATION_NAME, "XCUITest");
        caps.setCapability(MobileCapabilityType.NO_RESET, true);


        // Initialize the iOS driver
        IOSDriver<MobileElement> driver = null;
        try {
            driver = new IOSDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), caps);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }


        // Perform actions on the app
        MobileElement element = driver.findElement(By.id("element_id"));
        element.click();
        element.sendKeys("Hello World");


        // Assert element text
        assert element.getText().equals("Expected Text");


        // Take a screenshot
        File screenshotFile = driver.getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(screenshotFile, new File("path/to/save/screenshot.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }


        // Quit the driver
        driver.quit();
    }
}

```

Ensure that "your_device_name" and "your_device_udid" are replaced with the right names for your iOS devices, respectively, and the UDID (Unique Device Identifier) of your iOS device.
Also, make sure to provide appropriate path to your app’s file under the capability “App”

6. Customize the required capabilities:

Put the pertinent values for platformVersion, deviceName, and app in the feature property of the finished script. Your device's iOS version and “platformVersion” must match. Your iOS device should be identified by the name “deviceName”. The “app” should be either the path to your app’s file or the directory of the app you want to test.

7. Run the tests

Using your favorite IDE or development tool, create and run the tests.

Appium will interact with the Appium Server linked to iOS devices via WebDriverAgent to automate the testing process based on commands in the test script.

## Disadvantages of Appium:

Like any other software, Appium Inspector also has its own limitations. They are listed below;

**Older versions of Android are not supported:** The fact that the Appium Framework does not support an Android version older than 4.2 is a further major disadvantage of automated Android testing with Appium. This makes it difficult for developers to perform tests on a large number of devices and reduces the coverage of tests. But a combination between Appium and other frameworks such as Selendroid could solve this problem.

**Slower speed: ** Due to its structure, Appium is frequently slow. It takes considerable time to set up the server in several situations and therefore communication of each action requires a significant amount of time due to its architecture. The developers are often confronted with delays in testing cycles.

**Limitations in support for desktop applications:** Appium is mainly intended to test mobile apps and it does not provide significant support for desktop applications.

**Slow execution speed::**  In the execution of tests, particularly on real devices, Appium may sometimes be slow.

**Limited support for non-native applications:** Appium has limited support for apps that are not native, which might make it difficult to test them.

**Limited support for image recognition:**: it is not possible to test some types of applications on the Appium platform due to a lack of support for image recognition.

**Heavy maintenance:** You need to maintain the scripts you've written in Appium. It won't take too long if you just use Appium for a couple of tests. This could be a problem if you are an enterprise that has to run tests on Mobile Applications as part of your regression suite. Maintenance alone could lead to your business being more costly than it needs to be.


### conclusion

Appium assists developers and testers in their attempts to test mobile applications as a comprehensive and dependable automation framework. Mobile apps on various platforms can be utilized with simplicity thanks to their client-server design, multi-platform support, platform-specific automation drivers, compatibility with a wide range of programming languages, and extensive selection of client libraries. Appium expedites testing while providing accurate findings thanks to its usage of the JSON Wire Protocol and ability to interact with UI elements. By exploiting its open-source status and the large community support, Appium is a versatile framework that keeps revolutionizing how we test mobile applications.