Testing With Selenium WebDriver (82 Blogs) Become a Certified Professional
AWS Global Infrastructure

Software Testing

Topics Covered
  • Testing With Selenium WebDriver (72 Blogs)
SEE MORE

How To Use Desired Capabilities in Selenium?

Published on Oct 07,2024 35 Views

A passionate and knowledgeable tech enthusiast known for his expertise in the... A passionate and knowledgeable tech enthusiast known for his expertise in the world of technology and programming. With a deep-rooted passion for coding, Sarfaraz...

Introduction

Desired capabilities involve setting browser properties for Selenium automated testing with environment parameters such as browser type, version, and platform. This blog will explain desired capabilities in Selenium, their role for QA professionals, and how they can be effectively employed with Selenium and Appium testing, with examples. If you want to get more details about Selenium, you can visit this Selenium Tutorial.

What are the Desired Capabilities?

Selenium Desired Capabilities are key settings that describe the characteristics of the environment in which the test is going to run. Such configurations comprise browser name, Java version, platform, and other settings that are essential in ensuring the tests run smoothly in different environment settings. Desired capabilities in Selenium are stored as simple key-value pairs, typically in JSON, to enable testers to configure the test environment further to their preference.

In Appium, there is a similar thing called Desired Capabilities, which are used to configure the environment for testing mobile web applications. Again, for each automation session, Appium clients pass these capabilities in the form of key-value pairs to the Appium server, which assists in setting the right test environment.

With Selenium 4 and new versions, the Desired Capabilities class has been withdrawn in favor of the Options class. Nevertheless, it is still possible to use desired capabilities together with options for further customization. For Selenium beginners, more information is available at What is Selenium.

Why do QA’s need Desired Capabilities?

Quality Assurance (QA) uses desired capabilities to ensure that their automated tests perform to their expected capabilities. In other words, by changing the properties of the browser and the available test environment, the QA teams can create conditions for tests that benefit the achievement of certain goals and produce accurate results.

Desired Capabilities allow QA engineers to declare what browser type should be used, how long the test or, in general, the script should take, and other parameters that are crucial for the proper running of tests. This is especially useful with Web applications as the consequence of browser variations may be apparent here.

Desired capabilities in Selenium are helpful for QA teams because they allow efficient use of time and resources and exclude time-wasting debugging to identify issues that have been missed during the test cycles. Further, for the audience interested in mastering this area, you might consider enrolling in Selenium Online Training to get more information.

WebDriver driver;

String baseUrl , nodeUrl;

baseUrl = “https://www.facebook.com”;

nodeUrl = “http://192.168.10.21:5568/wd/hub”;
DesiredCapabilities capability = DesiredCapabilities.Chrome();

capability.setBrowserName(“chrome”);

capability.setPlatform(Platform.WIN8_1);

driver = new RemoteWebDriver(new URL(nodeUrl),capability);

driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(2, TimeUnit.MINUTES);

Want to become a QA Engineer? Check out this QA Automation Engineer Course today.

Methods in Desired Capabilities for Selenium

The Desired Capabilities class in Selenium offers several methods that allow testers to specify the required properties of the test environment.

Below are some key methods:

  • getCapability(): Retrieves the current system’s capabilities.
  • setCapability(): Declares the test environment’s properties, such as device name, OS name, version, and browser details.
  • getBrowserName(): Retrieves the browser name of the current system.
  • setBrowserName(): Sets the browser name for the test.
  • getVersion(): Retrieves the browser or OS version.
  • setVersion(): Defines the browser version or OS version for the test.
  • getPlatform(): Retrieves platform details.
  • setPlatform(): Defines platform details for the test.

These methods provide a flexible way to customize the test environment. Below is an example of how these methods can be used to set browser and platform configurations:


WebDriver driver;

String baseUrl , nodeUrl;

baseUrl = “https://www.facebook.com”;

nodeUrl = “http://192.168.10.21:5568/wd/hub”;


DesiredCapabilities capability = DesiredCapabilities.Chrome();

capability.setBrowserName(“chrome”);

capability.setPlatform(Platform.WIN8_1);


driver = new RemoteWebDriver(new URL(nodeUrl),capability);

driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(2, TimeUnit.MINUTES);

For more in-depth discussions on Selenium’s capabilities, feel free to browse our extensive Selenium Interview Questions.

Desired Capabilities in Selenium Testing for Various Browsers

Desired capabilities when using Selenium WebDriver are capable of setting different capabilities needed for different browsers, for instance, Chrome, Firefox, and Internet Explorer. Here is a brief explanation of how settings for desired capabilities differ across browsers:

Chrome Browser

ChromeDriver is a browser-specific driver that is integrated with the Selenium WebDriver to operate the Chrome browser. Driver preferences for ChromeDriver can be accomplished using Chrome options or a capability. ChromeOptions is one of those settings that determines Chrome’s properties—for instance, disabling the popup or the info bars and ensuring Chrome is headless.

Common ChromeOptions arguments:

  • Disable-popup-blocking
  • Disable-infobars
  • Make-default-browser
  • Headless
  • Incognito
  • Start-maximized

You can also set ChromeOptions in order to deal with browser extensions such as Adblocker according to the certain steps.


//Setting up capabilities to run our test script

ChromeOptions options = new ChromeOptions();

//Add Adblocker extension to Chrome

options.addExtensions(new File(“C:UsersDownloadsadblocker.crx”));

DesiredCapabilities capabilities = new DesiredCapabilities();

//Using Chrome Options with Desired Capabilities Class

capabilities.setCapability(ChromeOptions.CAPABILITY, options);

ChromeDriver driver = new ChromeDriver(capabilities);

Firefox Browser

Firefox uses FirefoxOptions in association with Desired Capabilities. This permits you to configure the Firefox browser’s properties, such as setting it to work in a private window, disabling browser notifications, and much more.


{

“capabilities”: {

“alwaysMatch”: {

“browserName”: “firefox”,

“browserVersion”: “60”

}

}

}

Internet Explorer

Internet ExplorerOptions can be used together with Desired Capabilities in Selenium to set various browser parameters. Some among them are turning off native events, enabling hover behavior to persist and running IE driver on either 32-bit or 64-bit mode.


if(driverParameter == null || driverParameter.equalsIgnoreCase(IE))

{

DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();

capabilities.setCapability(“requireWindowFocus”, true);

capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);

}

Desired Capabilities in Selenium Testing with Different Languages

Selenium works with multiple programming languages, including Java, Python, C#, and JavaScript. Depending on the language used, Desired Capabilities can be set in different ways.

 

Java

In Java things are slightly different; one can create Desired Capabilities objects and set properties, for instance, by calling setCapability() and setBrowserName(). All of the configurations are performed before the actual WebDriver is instantiated.


//Setting up Desired 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”);

// If this capability isn’t specified, it will just get any available one

capabilities.setCapability(“platform”, “win10”);

capabilities.setCapability(“build”, “SampleApp”);

capabilities.setCapability(“name”, “JavaSample”);

// To enable network logs

capabilities.setCapability(“network”, true);

// To enable step-by-step screenshot

capabilities.setCapability(“visual”, true);

// To enable video recording

capabilities.setCapability(“video”, true);

// To capture console logs

capabilities.setCapability(“console”, true);

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());

}

}

 

Python

In Python, Desired Capabilities are set using the DesiredCapabilities module. You can define properties like browser type, version, and platform in a similar way to Java.


def _get_desired_capabilities():

“””

“””

platform = _TEST_SETTINGS[‘PLATFORM’]

browser = _TEST_SETTINGS[‘BROWSER’]

version = _TEST_SETTINGS[‘VERSION’]

if platform and browser:

if platform and browser:

‘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@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)

C#

For C#, Desired Capabilities are configured using the DesiredCapabilities class and methods like SetCapability() and SetBrowserName().


//Setting up Desired Capabilities for Chrome

DesiredCapabilities capability = DesiredCapabilities.Chrome();

Environment.SetEnvironmentVariable(“webdriver.chrome.driver”, “Path to ChromeDriver.exe”);

//Accept all certificates

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();

//Add extension to Firefox browser

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(“local path to crx extension”));

DesiredCapabilities capabilities = new DesiredCapabilities();

capabilities.SetCapability(ChromeOptions.Capability, options);

DesiredCapabilities dc = DesiredCapabilities.Chrome();

dc.SetCapability(ChromeOptions.Capability, options);

IWebDriver driver = new RemoteWebDriver(dc);

Example of Desired Capabilities in Appium Testing

Desired Capabilities are also used in Appium, a tool for mobile application testing. When the new automation session begins, the Appium client makes a request to the Appium server with the Desired Capabilities mentioned in a JSON format.

Below is an example of how Desired Capabilities can be configured in Appium for an iOS device:


{

//device details

“platformName”: “iOS”,

“platformVersion”: “15”,

“deviceName”:  “iPhone 14”,

// XCUITest automation engine is used for iOS devices

“automationName”: “XCUITest”,

“browserName”: “Safari”,

“app”: “path for the application under test”

}

Desired Capabilities tell the driver to begin the mobile automation test on an iPhone 14 device, with the automation aftermarket called XCUITest, and with the Safari browser.

Appium supports various standard Desired Capabilities, including:

  • automationName: Describes the automation engine (e. g. , Espresso, XCUITest).
  • deviceName: Defines the kind of mobility allowed in a specific gadget.
  • platformName: Defines the type of use of the mobile.
  • platformVersion: Defines the version of the mobile platform that the application is to be developed in.
  • app: Has the option where it is possible to indicate a path to the application under test.
  • browserName: Actually it is used to set the browser for the automation test.

Conclusion

Desired Capabilities are an effective feature in Selenium and Appium testing because they help the tester to set conditions to the testing environment and to get the most truthful results. No matter which browser, operating system or language is used for development, Desired Capabilities offer the necessary freedom of automation testing.

FAQs

What is desired capability in Selenium?

Desired Capability in Selenium is a set of key-value pairs used to define properties of the test environment, such as browser type, version, and platform.

What is the difference between ChromeOptions and DesiredCapabilities?

ChromeOptions is a class used to customize Chrome browser properties, while DesiredCapabilities define the overall test environment. They can be used together for advanced configurations.

How to set Desired Capabilities in Selenium 4?

In Selenium 4, DesiredCapabilities have been deprecated and replaced by the Options class, which can be used to set browser properties.

How do I set desired capabilities in Selenium for Firefox?

Desired capabilities for Firefox can be set using FirefoxOptions along with methods to specify browser properties and test configurations.

Upcoming Batches For Selenium Course
Course NameDateDetails
Selenium Course

Class Starts on 23rd November,2024

23rd November

SAT&SUN (Weekend Batch)
View Details
Selenium Course

Class Starts on 25th November,2024

25th November

MON-FRI (Weekday Batch)
View Details
Selenium Course

Class Starts on 21st December,2024

21st December

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How To Use Desired Capabilities in Selenium?

edureka.co