Loading...

How to Write a Test Script With Selenium WebDriver and Appium Libraries

automated testing

Today's modern software developers need automated testing to produce excellent application results. Both Selenium WebDriver and Appium emerge as top choices for programmers because they handle the automation of web and mobile apps. These tools let you create test scripts that verify how browser and mobile applications behave across different electronic devices. Cloud mobile testing further enhances this process by allowing these scripts to run on various environments without the need for physical infrastructure.

This blog demonstrates how to develop test scripts using both Selenium WebDriver and Appium libraries. It also explains how cloud mobile testing can simplify cross-device and cross-platform checks without heavy setup. This piece shows readers how to work with Selenium WebDriver and Appium, leads them through setup, and demonstrates test script development for both tools while highlighting the benefits of cloud mobile testing for scalability and efficiency.

Introduction to Selenium WebDriver

Selenium WebDriver works as the most popular system for automating web browser operations. This system gives developers an interface to control web interactions and perform basic user tasks, plus check page elements. The Selenium WebDriver platform offers browser compatibility for different top choices like Chrome, Firefox, Safari, and Edge.

WebDriver offers faster and more dependable control over browsers since it does not rely on Selenium RC's remote mechanisms. WebDriver allows developers to write tests in Java, Python, C# Ruby, and JavaScript because it supports these programming languages.

Using Selenium WebDriver with Cloud-Based Platforms

Developers can use cloud-based testing platforms like LambdaTest for Selenium WebDriver browser testing across many devices and systems using its cloud platform without needing personal infrastructure. You can test more websites faster through LambdaTest's Selenium online service platform to reach better test speed results. Alongside web automation, LambdaTest also supports selenium mobile testing, enabling developers to validate mobile app behavior on different browsers and devices seamlessly.

In addition to its scalability, LambdaTest gives you tools that include live browser checks, full test status logs, recorded tests, and speed controls. These beneficial features help you find problems quickly while making your test executions work better at the same time. With the addition of selenium mobile testing, you can ensure both web and mobile experiences remain consistent, reliable, and user-friendly.

Introduction to Appium

As an open-source solution, Appium enables users to automate native mobile apps plus their hybrids and web versions across both iOS and Android platforms. The system delivers a strong API and works with several coding languages like Java, Python, and Ruby, along with Selenium WebDriver capabilities. Appium allows us to test mobile applications and web browsers, making it useful for all mobile tests.

Appium stands out because it connects to the WebDriver protocol, which lets users combine Selenium WebDriver without difficulty. Appium lets you perform testing both on real devices and virtual platforms including emulators and simulators.

Setting Up the Development Environment

We have to configure our testing environment before creating test scripts with Selenium WebDriver and Appium.

Installing Selenium WebDriver

Starting with Selenium WebDriver requires installing the Selenium WebDriver library as the first step. Install the package using a programming language manager according to your specifications.

For Python, run the following command:

pip install selenium
For Java, you can include the following dependency in your Maven pom.xml file:

org.seleniumhq.selenium
selenium-java
4.0.0

After installing the software, download the browser drivers Selenium ChromeDriver and GeckoDriver to support all tests. Download the browser driver that matches the exact version of the modern browser you plan to test.

Installing Appium

You need to install Node.js before using Appium because this platform relies on it for operation. You can start with Appium installation after Node.js setup by running this npm command:

npm install -g appium

To start using Appium you require setting up both the Appium installer and its desktop client for managing servers and viewing app elements.

Setting Up Appium for Mobile Testing

To test mobile with Appium you must prepare several requirements first.

  • Android Testing: For Android testing use Android Studio while making sure your device or emulator is ready. Before starting the process, you must configure your Android Studio SDK and platform tools while setting up your PATH environment variable.
  • iOS Testing: If you test iOS code on macOS you must first install Xcode and choose how to test the app through its virtual devices or real devices.

You can begin using the Appium server both from the command line and through our desktop application.

Writing a Test Script with Selenium WebDriver

After finishing your setup, you can start creating test scripts for Selenium WebDriver. We will develop basic test code to control web browsers automatically:

1. Basic Example: Automating Web Browser Actions

In this example, we’ll automate the process of opening a website and verifying the page title.

Python Example:

from selenium import webdriver
from selenium.webdriver.common.by import By
# Set up the WebDriver for Chrome
driver = webdriver.Chrome(executable_path="path/to/chromedriver")
# Open a website
driver.get("https://www.example.com")
# Verify page title
assert "Example Domain" in driver.title
# Find an element by its ID and click it
element = driver.find_element(By.ID, "some-id")
element.click()
# Close the browser
driver.quit()

In this script:

  • We initialize the WebDriver for Chrome and navigate to a URL.
  • We assert that the page title contains the expected string.
  • We locate an element by its ID and perform a click action on it.
  • Finally, we close the browser using driver.quit().

2. Running the Test Script

You can execute the script after completing its writing. Before script execution ensure either the browser drivers like ChromeDriver are properly set in the system's PATH environment variable or directly added in the script.

python test_script.py

If everything is set up correctly, the browser will open, the test actions will be performed, and the script will end when the browser closes.

Writing a Test Script with Appium

The following section focuses on the creation of test scripts by using Appium. Appium functions as an automated platform that enables users to perform tests on mobile devices or virtual devices for mobile applications.

1. Basic Example: Automating Mobile Actions

We will write code to control the launch and element selection operations within mobile applications operating on Android emulators.

Java Example:

import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.remote.MobileCapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.WebElement;
import java.net.URL;
public class AppiumTest {
public static void main(String[] args) throws Exception {
// Set up desired capabilities for Android device
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator");
capabilities.setCapability(MobileCapabilityType.APP, "path/to/your/app.apk");
// Create an instance of AndroidDriver
AndroidDriver driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
// Interact with UI elements
MobileElement element = driver.findElementById("com.example:id/button");
element.click();
// Verify some action
WebElement resultText = driver.findElementById("com.example:id/result");
assert resultText.getText().equals("Success");
// Close the session
driver.quit();
}
}

In this script:

  • We set up the desired capabilities, specifying the platform, device, and app path.
  • We create an instance of AndroidDriver and connect it to the Appium server.
  • We interact with a button by locating it via its ID and performing a click action.
  • We verify the result by checking the text of a WebElement.
  • Finally, we end the session with driver.quit().

2. Running the Test Script

To run the Appium test script, ensure that the Appium server is running and the emulator/device is set up. You can start the Appium server using:

Appium

Then, run the test script from your IDE or terminal.

Best Practices for Writing Test Scripts

To write effective and maintainable test scripts, keep the following best practices in mind:

1. Use Page Object Model (POM)

The Page Object Model is a test design technique that keeps test code structure efficient and cuts down common elements. It separates application testing into individual page groups to simplify development and maintenance operations. Through POM you can segregate UI locators and control flow that reduces the impact of UI updates on test code. The approach helps teams work better since it assigns separate tasks to each member.

2. Handle Synchronization

Ensure that your tests wait for elements to appear or become interactive before performing actions. Use explicit waits like WebDriverWait to avoid issues caused by timing problems. Synchronization ensures more stable test execution, especially in dynamic web or mobile environments where content loads asynchronously. Without proper waits, tests may fail due to race conditions or missing elements.

3. Modularize Tests

Split your test script functions into smaller parts to make them easier to read and easier to use again. Create separate methods to store groups of actions and validations for easy organization. Your updated tests are made easy when application logic changes since separate blocks help keep the entire test suite flowing well in the future.

4. Use Assertions

Verify the application's actions with assertions to find problems before they become major issues. The tests prove that the expected behavior works as intended in real situations. Adding test verification points makes your automation work better while showing problems in user behavior right away.

5. Run Tests in Parallel

To test faster, combining multiple devices and browsers runs through TestNG or Appium Grid. A wider testing range becomes available faster. Parallel execution creates the most speed benefits for developers working on CI processes since time is their main priority. Cloud testing service LambdaTest enables users to run automated tests simultaneously across many platforms.

6. Keep Test Data Externalized

Store test data in external files such as JSON, Excel, or CSV instead of hardcoding values in the test script. This separation improves maintainability and allows testers to update data without modifying the test logic. It also helps support data-driven testing, where the same test runs with multiple sets of input values for better coverage.

7. Use Meaningful Naming Conventions

Name all your test methods as well as variables and classes to match their intended application. The usage of descriptive names enhances program readability while helping team members understand what the test accomplishes through its quick assessment. A consistent naming convention also enhances collaboration and debugging efficiency.

8. Implement Proper Logging and Reporting

Include logs and structured reports in your test scripts to track test execution and easily identify issues. Logs provide step-by-step execution details, while reports give summaries of passed, failed, and skipped tests. Additionally, recent advancements like AI in testing can help analyze these logs to predict failures and optimize test coverage more intelligently.

In Conclusion

Test script development with Selenium WebDriver and Appium forms the essential mandatory competency for current-day testers and developers. The tools grant teams the ability to automate testing for web and mobile applications that provide consistent, fast results with improved test coverage. The blog presents a practical process from installation and setup for automation of these platforms, followed by script-writing guidance.

Such libraries gain exceptional capability when joined with LambdaTest cloud tools because they enable scalable operations and multiple platform accessibility and speed up test execution times. Building test scripts that combine robust behavior with scalability occurs when you implement best practices through Page Object Model usage alongside synchronization management together with test modularity and the addition of assertions.

The synergy between Selenium and Appium enables the testament of responsive websites across browsers and mobile apps across devices in a streamlined way. Begin with simple test cases followed by regular experimentation then develop your scripts to match actual application levels.

Copyright © All Rights Reserved