Streamline Mobile Browser Testing with Selenium
As a testing expert with over 10 years of experience, I have witnessed the rapid growth of mobile traffic first-hand. Validating website functionality on smartphones and tablets has become indispensable today. In this guide, let me walk you through mobile browser test automation with Selenium.
Why Mobile Browser Testing Matters
Mobile devices now drive 58% of internet traffic globally. And this share is estimated to grow to over 75% by 2025 according to Statcounter.
| Year | Mobile Share | Desktop Share |
|---|---|---|
| 2022 | 58.3% | 41.7% |
| 2025 | 75% to 80% | 20 to 25% |
Hence, delivering reliable cross-device web experiences is vital for businesses today. Manually testing each device, OS and browser combination is tedious. Test automation provides the scale and speed crucial for mobile-first development.
This is where Selenium shines. The popular open-source tool helps streamline browser validation across mobiles, desktops and tablets. Let‘s see how to leverage it for testing mobile websites.
Selenium for Mobile Browser Test Automation
Selenium supports automating Chrome, Safari and native browser apps on mobile devices. iOS or Android environment can be configured seamlessly through desired capabilities.
Key highlights:
- Supports Java, C#, Python, JavaScript and Ruby languages
- Easy integration with frameworks like TestNG, JUnit for test reports
- Parallel execution across hundreds of devices through Selenium Grid
- Open source and community backed with strong developer support
In addition, Appium extensions help test hybrid mobile apps, payment flows and location APIs. Detailed element selectors provide precision in targeting specific mobile UI components.
Let‘s set up Selenium and write sample test scripts for mobile browsers.
Setting up Selenium Test Environment
Here are the minimal prerequisites to start test automation with Selenium:
Step 1: Install Android SDK
Download the command line tools for your OS from developer.android.com and set the ANDROID_HOME system variable pointing to the extracted location.
For example,
export ANDROID_HOME=/Users/testrunner/android/sdk
export PATH=$PATH:$ANDROID_HOME/platform-tools
This provides adb and other binaries to detect connected Android devices.
Step 2: Install Appium Server
Appium acts as the intermediary server between test scripts and mobile devices. Install it globally using npm:
npm install -g appium
appium #Start server at localhost:4723
Step 3: Set Desired Capabilities
Define the target device details and browser in test scripts through DesiredCapabilities:
DesiredCapabilities caps = new DesiredCapabilities();
// Set device details
caps.setCapability("deviceName", "iPhone 14");
caps.setCapability("platformVersion", "iOS 16.1");
// Specify browser
caps.setCapability("browserName", "Safari");
This configures tests to run on the defined mobile device, OS and browser combination.
Step 4: Run Selenium Test Scripts
Java example to open url and validate title:
//Initialize driver
AppiumDriver driver = new IOSDriver(new URL("http://localhost:4723/"), caps);
// Browser test steps
driver.get("https://www.example.com");
Assert.assertEquals("Example Domain", driver.getTitle());
driver.quit();
This will automate the website on the iPhone 14 mobile Safari browser. Let‘s explore more examples.
Sample Test Automation Scripts
Here are some common test scenarios for mobile browsers and websites:
1. Validate Cross-Device Responsiveness
Browser resolution impacts page rendering. To validate consistency:
// iPhone device
caps.setCapability("deviceName", "iPhone 14 Pro");
// Open page
driver.get("https://www.example.com");
int iphoneWidth = driver.manage().window().getSize().getWidth();
// Samsung device
caps.setCapability("deviceName","Samsung Galaxy S23");
// Get viewport width
int samsungWidth = driver.manage().window().getSize().getWidth();
// Assert for responsiveness
Assert.assertEquals(true, iphoneWidth <= samsungWidth);
Similar validation can be done across 10+ device combinations through test parameterization.
2. Verify Mobile Gestures
Pinch zoom, swipe and long tap are integral to mobile UX. To automate:
// Element for gesture
MobileElement menu = (MobileElement) driver.findElement(MobileBy.id("menu"));
// Tap event
menu.tap(TapOptions.tapOptions().withTapsCount(3));
// Pinch zoom
MultiTouchAction zoom = new MultiTouchAction(driver);
zoom.add(TouchAction.longPress(menu).moveTo(PointOption.point(0,700)).release());
// Validate text visibility
Assert.assertTrue(menu.isDisplayed());
3. Native App Testing
Selenium allows testing native mobile applications like Gmail, Maps or Browser.
For example, here is the script to validate the Chrome app on Android:
// Set native app capabilities
caps.setCapability("appPackage", "com.android.chrome");
caps.setCapability("appActivity","com.google.android.apps.chrome.Main");
// Start app
driver.launchApp();
// Validate element
MobileElement searchBox = (MobileElement) driver.findElement(MobileBy.id("search_box_text"));
Assert.assertTrue(searchBox.isEnabled());
This unlocks testing opportunities beyond just websites!
Best Practices for Test Automation
Here are some tips from my decade long experience in browser test automation:
1. Build Reusable Page Objects
Page object model minimizes duplicate locators and improves code reuse across test scripts.
public class LoginPage {
WebDriver driver;
By username = By.id("userid");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void loginAs(String user) {
driver.findElement(username).sendKeys(user);
driver.findElement(By.id("signin")).click();
}
}
And call it:
LoginPage login = new LoginPage(driver);
login.loginAs("tester123");
2. Parameterize Data
Dynamic test data helps cover more scenarios:
// Test data array
String[] users = {"normaluser", "admin123", "testuser"};
@Test
public void loginTest() {
String user = users[Math.random()*users.length];
LoginPage login = new LoginPage(driver);
login.loginAs(user);
}
3. Divide Execution Across Threads
Group test cases into suites and segregate using TestNG xml:
<!DOCTYPE suite SYSTEM "testng.org/testng-1.0.dtd" >
<suite name="Mobile Browser Automation" parallel="tests" thread-count="3">
<test name="ChromeTest">
<classes><class name="ChromeBrowserTests"/></classes>
</test>
<test name="SafariTest">
<classes><class name="SafariBrowserTests"/></classes>
</test>
</suite>
This allows parallel test execution across mobile device groups.
Real Device Cloud for Easier Cross Browser Testing
While Selenium eases mobile browser automation, setting up each physical device with browsers still requires effort.
BrowserStack‘s mobile device cloud overcomes this complexity with instant access to 3000+ real mobile devices. This means you can test Safari on iPad Pro 12.9 instantly without hassles of procurement and management.
Here is a Selenium script to test on BrowserStack:
//Set BrowserStack credentials
String username = "user1234";
String accessKey = "abcd1zyx2";
//Capabilities
caps.setCapability("device", "iPhone 12");
caps.setCapability("osVersion", "14");
caps.setCapability("browserName", "safari");
//Create driver instance
AppiumDriver driver = new IOSDriver(
new URL("https://" + username + ":" + accessKey + "@hub-cloud.browserstack.com/wd/hub"),
caps);
// Execute test scenario
driver.get("https://www.example.com");
Assert.assertEquals(driver.getTitle(),"Example Domain");
driver.quit();
This cloud offers debugging ability, geo-location testing, console logs and video recording to debug complex issues faster.
Conclusion
I hope this guide gave you a firm grounding in mobile browser test automation approaches using Selenium. Automating these validations provides confidence for your entire web development team.
With cloud testing services like BrowserStack, you can focus on writing test scripts rather than device configurations. Collaborating selenium automation with CI/CD pipelines helps shift testing left and catch cross-browser issues early.
As an app quality veteran myself, I highly recommend investing in browser test automation for delivering engaging mobile web experiences. Feel free to reach out for any queries!