Desired Capabilities in Selenium Testing With Examples
Find out what desired capabilities are and how to achieve them in Selenium testing using different methods and different browsers.
Join the DZone community and get the full member experience.
Join For FreeDesired Capabilities is a class used to declare a set of basic requirements such as combinations of browsers, operating systems, browser versions, etc. to perform automated cross-browser testing of a web application.
When we try to automate our test scripts through Selenium automation testing, we need to consider these combinations to declare a specific test environment over which our website or web application should render seamlessly.
These environments can be mobile devices, mobile browsers, desktop devices, desktop browsers, screen resolutions, etc. To declare these environments in our Selenium automation testing script, we make use of the Desired Capabilities in Selenium testing or Appium testing and this is exactly what we will be discussing in this article.
I will help you become familiar with the Desired Capabilities in Selenium testing and Desired Capabilities for Appium too. I will show you what they are, how they are used for Selenium automation testing and Appium testing with examples. Without further ado, let’s get started.
What Are Desired Capabilities?
Desired Capabilities class is a component of the org.openqa.selenium.remote.DesiredCapabilities
package. It helps Selenium WebDriver set the properties for the browsers. Using different capabilities from Desired Capabilities class we can set the properties of browsers. For example, the name of the browser, the version of the browser, etc. We use these capabilities as key-value pairs to set them for browsers.
You can refer to the GitHub library for the Desired Capabilities for all the detailed methods, etc.
While working with Selenium automation testing, we always have different requirements while execution specifically about which browser to execute, which operating system and version to use for test execution, this where Desired Capabilities helps us a lot on Selenium Grid.
To declare Desired Capabilities in Selenium automation testing using Grid, we can use the setCapability method from the DesiredCapabilities class to set the different types of capabilities of the browser (Ex. Chrome, IE, Firefox, Edge) platform name (Ex. Windows, macOS, etc.).
Desired Capabilities in Appium is useful in the case of mobile application automation, where we have to execute test automation on different browser properties and device properties, which we can set using Desired Capabilities class.
To leverage automation testing for different types of mobile devices, the different kinds of mobile platforms like iOS, Android, etc. Also, there can be different platform (operating system) versions like for Android 9.x, 10.x and for iOS 12.x, 13.x, etc, we can set these properties using Desired Capabilities in Appium for Android or iOS as per our requirement.
There Is More To Desired Capabilities In Selenium And Appium
Using Desired Capabilities class, we instruct the WebDriver about the environment like browser name, browser version, platform, etc. over which we perform automated browser testing using our automation scripts. But that is not all we can do using the Desired Capabilities class. We can also configure browser-specific preferences such as enabling chrome options, firefox options, testing with incognito mode or even disabling javascript, etc.
If you are using a cloud-based online Selenium grid, then the Desired Capabilities class can also be used to perform parallel testing with Selenium or Appium, testing locally hosted web applications with Selenium, generating command-by-command screenshots, or even a video recording of the entire test automation execution over different browsers + OS configurations.
Types Of Desired Capabilities Methods
Now, let us discuss the different methods available in Desired Capabilities class to set the different properties in test automation.
getCapability():
public java.lang.Object getCapability(java.lang.String capabilityName)
This method getCapability() from the class Desired Capabilities, which can be used to get the capabilities of the current system which we are using.
setCapability()
public java.lang.Object getCapability(java.lang.String capabilityName)
This method setCapability() from the class Desired Capabilities, can be used to set the name of the device, name of the platform, version of the platform, absolute path of the application which is under test, application activity (in Mobile automation), application Package (in Java), etc.
getBrowserName():
public java.lang.String getBrowserName()
This method getBrowserName() from the class Desired Capabilities, can be used to get the name of the Browser.
setBrowserName()
public void setBrowserName(java.lang.String browserName)
This method setBrowserName() from the class Desired Capabilities, can be used to set the name of the Browser.
getVersion()
This method getVersion() from the class Desired Capabilities, can be used to get the version of the browser or platform.
public java.lang.String getVersion()
setVersion()
public void setVersion(java.lang.String version)
This method setVersion() from the class Desired Capabilities, can be used to set the version of the browser or platform.
getPlatform()
public Platform getPlatform()
This method getPlatform() from the class Desired Capabilities, can be used to get the details of the platform.
setPlatform()
public Platform setPlatform()
This method setPlatform() from the class Desired Capabilities, can be used to set the details of the platform.
For more information, you can refer to Selenium documentation.
Desired Capabilities In Selenium Testing For Different Browsers
In the above section, we have seen different methods of Desired Capabilities class. Now, let us discuss how we can set different capabilities for different browsers.
Desired Capabilities in Selenium WebDriver for Chrome
When we want to customize and configure the Desired Capabilities in Selenium WebDriver for Chrome, we need to invoke the ChromeDriver session to leverage these capabilities. So let us discuss capabilities that are supported by ChromeDriver and how we can use them to set those desired capabilities in Selenium Webdriver for Chrome.
There are two ways to set the capabilities for ChromeDriver.
1. ChromeOptions.
2. Desired Capabilities.
ChromeOptions is another class that can be used in conjunction with Desired Capabilities in Selenium WebDriver for Chrome to customize or manipulate the various properties of the Chrome browser.
The following are the commonly used arguments from the ChromeOptions class.
Disable-infobars: It is used to prevent chrome browser from displaying notifications like “Chrome is being controlled by automated software”.
Make-default-browser: It is used to make the Chrome browser as the default browser.
Disable-popup-blocking: It is used to disable the pop-ups which are displayed on the chrome browser.
Incognito: It opens the chrome browser in incognito mode.
Start -maximized: It opens the chrome browser in maximized mode.
Headless: It is used to open the chrome browser in headless mode.
Now, let us discuss an example of an ad blocker where Chrome Option is used in conjunction with Desired Capabilities class. We will use an adblocker extension for this purpose.
Prerequisite for that a crx file of the extension should be downloaded.
//Setting up capabilities to run our test script
ChromeOptions opt = new ChromeOptions();
opt.addExtensions(new File(“path for crx file of the extension”));
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
ChromeDriver driver = new ChromeDriver(capabilities);
Desired Capabilities in Selenium WebDriver for Firefox
Like we have seen in the case of the Chrome browser, there are also ways to customize the Desired Capabilities in Selenium WebDriver for Firefox browsers.
moz:firefoxOptions capability is available specifically for the Firefox browser. We can use moz:firefoxOptions to customize or manipulate different properties of the Firefox browser, which helps us to control the behavior of the Firefox browser. It is usually invoked as a member in either of the two, one is from alwaysMatch and the other is from firstMatch entries.
moz:firefoxOptions can contain the following things that can control how Firefox browser starts or runs.
a) Binary(String): We provide an absolute path for the custom Firefox binary to use. Normally, GeckoDriver which is a driver that we use for Firefox tries to find the location of Firefox on the current system if it is not defined.
b) Args(array of strings): This argument is used to pass the command line arguments to the Firefox binary. While using this syntax should contain, hyphen/dash like [“-profile”].
So to pick up the existing profile by GeckoDriver, we should use syntax like
[“-profile”, “path to the profile”]
c) Profile(string): We can provide the path for the directory so that Firefox instance can be used. For installing some firefox extensions or some custom certificates, we can use this. While it is recommended to use prefs while we want to set the custom preferences, instead of directly passing the profile. You can find the example of prefs below along with others.
Here is an example of declaring Desired Capabilities in Selenium WebDriver for Firefox.
{
"capabilities": {
"alwaysMatch": {
"moz:firefoxOptions": {
"binary": "/usr/local/firefox/bin/firefox",
"args": ["-headless", "-profile", "/path/to/my/profile"],
"prefs": {
"dom.ipc.processCount": 9,
"javascript.options.showInConsole": true
},
"log": {"level": "trace"}
}
}
}
}
if(driverParameter == null || driverParameter.equalsIgnoreCase(FIREFOX))
{
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
FirefoxOptions options = new FirefoxOptions();
options.setHeadless(headless);
capabilities.merge(options);
}
Desired Capabilities in Selenium WebDriver for IE(Internet Explorer)
Now, let us proceed with Desired Capabilities in Selenium WebDriver for IE(Internet Explorer). For IE, we make use of InternetExplorerOptions with Desired Capabilities in Selenium WebDriver.
Here is an example of declaring Desired Capabilities in Selenium WebDriver for IE.
if(driverParameter == null || driverParameter.equalsIgnoreCase(IE))
{
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
InternetExplorerOptions option = new InternetExplorerOptions();
option.setHeadless(headless);
capabilities.merge(option);
}
There are few Internet Explorer specific capabilities which we can use, let us discuss some of them one by one.
a) IgnoreZoomSetting(boolean): This capability can be used to ignore checking the browser’s zoom level to 100%. By default, it is set as false. It takes a boolean value as input.
b) InitialBrowserUrl(string): Using this capability we can decide the initial URL, the website to which it should redirect while internet explorer browser starts. It takes a string as input.
c) EnableElementCacheCleanup(boolean): This capability provides a check over the obsolete elements from element cache. If they are found then the capability instructs the WebDriver to clean up. It takes a boolean value as input.
d) RequireWindowFocus(boolean): This capability is used for instructing the driver to check that the internet explorer window has the focus before performing any operations like a mouse or keyboard events etc. It takes a boolean value as input and by default, it is set as false.
e) IgnoreProtectedModeSettings(boolean): If you wish to skip past the protected mode check while performing Selenium automation testing then you can leverage this capability. It takes a boolean value as input.
These are some of the Internet Explorer specific capabilities which we can use.
Examples Of Desired Capabilities In Selenium Testing With Different Languages
Now, I will demonstrate to you how to leverage Desired Capabilities in Selenium testing with different languages. As you may already know, Selenium automation testing is supported by multiple programming languages.
It offers bindings for every major programming language i.e. JavaScript, C#, Python, Java, Ruby, PHP. To give you a gist of how you can leverage the desired capabilities in Selenium testing, I will be giving examples for Java, C#, and Python.
Desired Capabilities in Selenium WebDriver for Java
//Setting up capabilities to run our test script
@BeforeClass
public void setUp() throws Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("browserName", "chrome");
capabilities.setCapability("version", "77.0");
capabilities.setCapability("platform", "win10"); // If this cap isn't specified, it will just get any available one
capabilities.setCapability("build", "LambdaTestSampleApp");
capabilities.setCapability("name", "LambdaTestJavaSample");
capabilities.setCapability("network", true); // To enable network logs
capabilities.setCapability("visual", true); // To enable step by step screenshot
capabilities.setCapability("video", true); // To enable video recording
capabilities.setCapability("console", true); // To capture console logs
capabilities.setCapability("selenium_version","4.0.0-alpha-2");
capabilities.setCapability("timezone","UTC+05:30");
capabilities.setCapability("geoLocation","IN");
capabilities.setCapability("chrome.driver","78.0");
try {
driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), capabilities);
} catch (MalformedURLException e) {
System.out.println("Invalid grid URL");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
Desired Capabilities in Selenium WebDriver for C#
//Accept all certificates Chrome
DesiredCapabilities capability = DesiredCapabilities.Chrome();
Environment.SetEnvironmentVariable("webdriver.chrome.driver", "Path to ChromeDriver.exe");
capability.SetCapability(CapabilityType.AcceptSslCertificates, true);
IWebDriver driver = new RemoteWebDriver(capability);
//Set Chrome options.
ChromeOptions options = new ChromeOptions();
DesiredCapabilities dc = DesiredCapabilities.Chrome();
dc.SetCapability(ChromeOptions.Capability, options);
IWebDriver driver = new RemoteWebDriver(dc);
//Turn off the JavaScript Firefox
FirefoxProfileManager profileManager = new FirefoxProfileManager();
FirefoxProfile profile = profileManager.GetProfile("TestProfile");
profile.SetPreference("javascript.enabled", false);
IWebDriver driver = new FirefoxDriver(profile);
//Set the default page load timeout
driver.Manage().Timeouts().SetPageLoadTimeout(new TimeSpan(10));
//Start Firefox with plugins
FirefoxProfile prof = new FirefoxProfile();
profile.AddExtension(@"C:Location of extension.xpi");
IWebDriver driver = new FirefoxDriver(prof);
//Start Chrome with an unpacked extension
ChromeOptions options = new ChromeOptions();
options.AddArguments("load-extension=/pathTo/extension");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.SetCapability(ChromeOptions.Capability, options);
DesiredCapabilities dc = DesiredCapabilities.Chrome();
dc.SetCapability(ChromeOptions.Capability, options);
IWebDriver driver = new RemoteWebDriver(dc);
//Start Chrome with a packed extension
ChromeOptions options = new ChromeOptions();
options.AddExtension(Path.GetFullPath("localpathto/extension.crx"));
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.SetCapability(ChromeOptions.Capability, options);
DesiredCapabilities dc = DesiredCapabilities.Chrome();
dc.SetCapability(ChromeOptions.Capability, options);
IWebDriver driver = new RemoteWebDriver(dc);
Desired Capabilities in Selenium WebDriver for Python
def _get_desired_capabilities():
"""
"""
platform = _TEST_SETTINGS['PLATFORM']
browser = _TEST_SETTINGS['BROWSER']
version = _TEST_SETTINGS['VERSION']
if platform and browser:
capabilities = {
'platform': platform,
'browserName': browser,
'version': version,
}
elif browser.lower() == 'firefox':
capabilities = DesiredCapabilities.FIREFOX
else:
capabilities = DesiredCapabilities.CHROME
return _add_travis_info(capabilities)
def run_browser(self,os_name,os_version,browser,browser_version):
USERNAME = ‘test.lambdatest@gmail.com’
PASSWORD = ‘Test123’
if browser.lower() == 'ff' or browser.lower() == 'firefox':
desired_capabilities = DesiredCapabilities.FIREFOX
elif browser.lower() == 'ie':
desired_capabilities = DesiredCapabilities.INTERNETEXPLORER
elif browser.lower() == 'chrome':
desired_capabilities = DesiredCapabilities.CHROME
elif browser.lower() == 'opera':
desired_capabilities = DesiredCapabilities.OPERA
elif browser.lower() == 'safari':
desired_capabilities = DesiredCapabilities.SAFARI
desired_capabilities['os'] = os_name
desired_capabilities['os_version'] = os_version
desired_capabilities['browser_version'] = browser_version
return webdriver.Remote(RemoteConnection("http://%s:%s@hub-cloud.browser.com/wd/hub"%(USERNAME,PASSWORD),resolve_ip= False),
desired_capabilities=desired_capabilities)
Example For Desired Capabilities In Appium Testing
When a new automation session is requested, the Appium client sends a request to the server with a JSON object which includes Desired Capabilities in the form of key and value pairs.
Using these keys and values from the JSON object, we provide decide and instruct appium drivers about how we want our mobile automation test to work.
Desired Capabilities can then be set within a server of Appium or we can also add it in our Webdriver test script.
Following is an example of desired capabilities in Appium testing using a JSON object:
{
“platformName”: “Android”,
“platformVersion”: “10.0”,
“deviceName”: “Samsung Galaxy s10”,
“automationName”: “Appium”,
“app”: “path for the app under test”
}
So using the above-desired capabilities in Appium testing through a JSON object, we are instructing drivers to start our mobile automation session on device Samsung Galaxy s10 with Android version 10.0 using Appium and for the app with the given file location.
There are different desired capabilities Appium supports, out of which some capabilities are common for all the platforms or drivers, while some are driver or platform-specific. Let us discuss some of them as we proceed further.
General or Standard Desired Capabilities in Appium Testing
- AutomationName: Using this capability we can instruct drivers about which automation engine it should use. By default, it is set as Appium. Other available engines like Appium, Espresso (both are for android), XCUITest (for iOS)
- PlatformName: We can use this to instruct the mobile operating system platform like iOS, Android, etc.
- PlatformVersion: We can use this for mentioning the mobile operating system version on which test expect to execute.
- DeviceName: We can use this to specify the particular mobile device over which we wish to perform automated browser testing. Like we have used Samsung Galaxy s10 in the above example.
- App: This capability is used to provide the path of our application which needs to be tested with the script. Here we provide an absolute local path or remote path with HTTP URL.
- BrowserName: This can be used when we want to execute a test on a mobile web browser. We can provide the name of the browser like Safari for iOS, Chrome for Android, etc. It can be left empty when we want to automate the app and not using a browser.
- Language: This can be used to set the language of Android or iOS.
- NewCommandTimeout: This capability helps to instruct drivers for the time it has to wait for a new command from the client before ending the idle session.
There are a few more general capabilities like noReset, fullReset,eventTimings, etc.
Desired Capabilities In Appium For Android
- AppActivity: Use this capability to declare a name for an Android activity that you wish to launch from the package. Such as: .MainActivity, .Settings
- AppPackage: Using this capability, we decide the JAva package of the Android app which we want to execute. By default package manifest provides this capability.E.g. com.example.android.testApp
- AppWaitActity: This capability provides the name of android activity we want to wait.
- AppWaitPackage: This provides java package for an android app that we want to wait for.
- AppWaitDuration: This capability used to instruct the wait in milliseconds for the appWaitActivity to launch.
- DeviceReadyTimeout: This capability instructs about a timeout in seconds while the driver is waiting for the device under test to become ready.
Apart from the above android capabilities, there are few more like adbPort, systemPort, remoteAdbHost, androidInstallPath, etc.
Desired Capabilities In Appium For iOS
- CalendarFormat: This capability can be used to set the calendar format for the iOS simulator. E.g. Gregorian
- LaunchTimeout: This capability instructs about the time in milliseconds up to which driver has to wait and after that it considers session as failed or hung.
- AutoAcceptAlerts; This capability is used to accept all the iOS alerts, if they popup while performing automated browser testing. Examples: privacy access permission alerts like location, contacts, etc.
- AutoDismissAlerts: This capability is used to decline/dismiss all the iOS alerts when they popup while performing automated browser testing. Examples: privacy access permission alerts like location, contacts, etc.
- SafariInitialUrl: Using this capability we can set the initial URL for the safari browser, so it works as a welcome page when browser launches.
- AppName: This capability used to display the name of the application which is under test.
Apart from the above iOS capabilities, there are few more like safariAllowPopups, customSSLCert, etc.
So we have seen desired capabilities that we can use while creating a test with examples for different browsers, with different languages and we also discussed it for Appium with different platforms/operating systems.
What Have We Learned
As we perform Selenium automation testing we need to declare a set of basic requirements regarding the test environment such as specific browsers, operating systems, and more. This is achieved using the Desired Capabilities class for Selenium testing and Appium testing.
We can also specify the conditions over which we need to perform the test such as locally hosted testing, parallel testing, testing with javascript disabled and more.
Happy testing!
Further Reading
Published at DZone with permission of Ramit Dhamija. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments