Wednesday, 1 March 2017

Selenium commands, C# vs. Java

Selenium commands, C# vs. Java

The differences.

From V5 of the book The Agile Software Tester

by Kevin C Martin

Due for release in the Summer of 2017 

For my other Selenium blogs go here - www.kevsbox.com

Finding elements

No matter if you are using Java or C#, one of the critical requirements of automated testing will always be the ability to identify and locate elements from the web page under test and then being able to perform tests on these elements that will confirm the data returned is both valid and correct. This means that the test tool in use must be able to recognise the web elements quickly, correctly and effectively.

Selenium WebDriver is a tool that provides one of the most advanced techniques for locating elements on web pages in various popular web browsers. Selenium's very feature-rich API provides reliable multiple locator strategies such as ID, Name, CSS selectors, XPath etc. With Selenium, you are also able to implement custom locator strategies for locating elements. Essentially these locators are the mainstay of your tests. Using the right locator for the situation ensures the tests are faster, more reliable and have a lower maintenance overhead in future releases. In any web development project regardless of what development language is being used, it is always good practice to assign meaningful attributes such as Name, IDs or Class to all of the elements that exist on the web page. This makes the application more readable, testable and conforms to existing accessibility standards. There are rare occasions, however, when following these practices is simply not possible. For such scenarios, you will have to use advanced locator strategies such as CSS selector and the XPath function.

While both CSS selector and XPath are popular among most Selenium users, the CSS selector option is always recommended over XPath due to its simplicity, speed, and performance advantages.

Locating elements in Selenium WebDriver is done by using the findElement() and findElements() methods provided by WebDriver and WebElement class.

The findElement() method returns a WebElement object based on a specified search criteria or throws up an exception if it does not find any element matching the search criteria.

The findElements() method returns a list of WebElements matching the search criteria. If no elements are found, it returns an empty list.

Find methods take a locator or query object as an instance of By class as an argument. Selenium WebDriver provides By class to support various locator strategies.

The following table lists various locator strategies currently supported by the Selenium WebDriver:



Strategy
Syntax
By ID
Java: driver.findElement(By.id(<element ID>))

C#: driver.FindElement(By.Id(<elementID>))
By name
Java: driver.findElement(By.name(<element name>))

C#: driver.FindElement(By.Name(<element name>))
By class name
Java: driver.findElement(By.className(<element class>))

C#: driver.FindElement(By.ClassName(<element class>))
By tag name
Java: driver.findElement(By.tagName(<htmltagname>))

C#: driver.FindElement(By.TagName(<htmltagname>))
By link text
Java: driver.findElement(By.linkText(<linktext>))

C#: driver.FindElement(By.LinkText(<linktext >))
By partial link
Java: driver.findElement(By.partialLinkText(<linktext>))

C#: driver.FindElement(By.PartialLinkText(<linktext >))
By CSS
Java: driver.findElement(By.cssSelector(<css selector>))

C#: driver.FindElement(By.CssSelector(<css selector >))
By XPath
Java: driver.findElement(By.xpath (<xpath query expression>))

C#: driver.FindElement(By. XPath(<xpath query expression>))



Locating elements using id, name, or class attributes are the preferred way to find elements in Selenium.  So let's try using these methods to locate elements as described in the following sections.
Locate by ID
By far Ids is the preferred method to locate elements on a web page. This is because The W3C standard recommends that developers provide an id attribute for elements that are unique to each element. Having a unique id attribute provides a very explicit and reliable way to locate elements on the page. If for any reason the Ids are not unique or they are auto-generated this method should not be used.
With this method, the first element with the id attribute value matching the location will be returned. If no element has a matching id attribute, a NoSuchElementException will be raised.
Below is an example of how to use this method
<form name="userId">Login
 User ID: <input id="userid" type="text" name="login" />
 Password: <input id="password" type="password" name="password" />
 <input type="submit" name="signin" value="SignIn" />
</form>
As you can see both input box have an id value, these can be used to locate the element. The example code for this is shown below.
WebElement elementUsername = driver.findElement (By.id ("userid"));

Locate by Name
The name attribute is another fast way to locate an element. However, you must also be aware that the name may not be unique. With this method the first matching element will be returned, if no element has a matching name attribute, a NoSuchElementException will be raised.
Below is an example of how to use this method
<form name="userId">Login
 User ID: <input id="userid" type="text" name="login" />
 Password: <input id="password" type="password" name="password" />
 <input type="submit" name="signin" value="SignIn" />
</form>
As you can see both input box have an id value, these can be used to locate the element. The example code for this is shown below.
WebElement elementUsername = driver.findElement (By.name ("login"));


Locate by XPath
XPath is the language used for locating nodes in any XML document. As HTML can also be an implementation of XML (XHTML), you lucky Selenium users can utilise this powerful language to locate elements in the web applications under test. XPath extends way beyond the simpler methods of locating by id and name attributes, it opens up new possibilities such as locating the fifth checkbox on the web page under test.

One of the main reasons for using XPath is when you don’t have a suitable id or name attribute for the element you wish to locate (for example they are not unique). You can use the XPath feature to either locate the element in absolute terms or relative to an element that does have an id or name attribute. This is not as preferred as ID or Name and can make your test cases less robust but there are times when no other option is available.
Below is an example of how to use this method
<html>
<html> <body>
  <form id="loginForm">
   <input name="userid" type="text" />
   <input name="password" type="password" />
   <input name="cButton" type="submit" value="Login" />
   <input name="cButton" type="button" value="Clear" />
  </form>
</body><html>

In this example the form elements can be located like this:
·         login_form = driver.find_element_by_xpath("/html/body/form[1]")
·         login_form = driver.find_element_by_xpath("//form[1]")
·         login_form = driver.find_element_by_xpath("//form[@id='loginForm']")

The username element can be located like this:
·         username = driver.find_element_by_xpath("//form[input/@name= userid]")
·         username = driver.find_element_by_xpath("//form[@id='loginForm']/input[1]")
·         username = driver.find_element_by_xpath("//input[@name= userid]")


Locate by LinkText and PartialLinkText
This is a very useful method to use when you know what the link text will be within an anchor tag. With this method, the first element with the link text value matching the location will be returned. If no element has a matching link text attribute, a NoSuchElementException will be raised instead.
Below is an example of how to use this method
<html> <body>
  <p>Are you sure you want to delete this record?</p>
  <a href="delete.html">Confirm</a>
  <a href="cancel.html">Cancel</a>
</body><html>
The find by link command will be
·         continue_link = driver.find_element_by_link_text('Confirm')
Also the find by partial link will be
·         confirm_link = driver.find_element_by_partial_link_text('Confi')

Locate by Tag Name

Use this when you want to locate an element by tag name. This is a limited method which is used less frequently than the methods already discussed. With this method, the first element with the given tag name will be returned. If no element has a matching tag name, a NoSuchElementException will be raised instead.
Below is an example of how to use this method
<html> <body>
  <h1>Welcome to Kevsbox.com</h1>
  <p>This is one cool site</p>
</body><html>   
The find by link command will be
·         headingLink = driver.find_element_by_tag_name('h1')


Locate by CSS
(Cascading Style Sheets)
Use this method when you want to locate an element by CSS selector syntax. With this method, the first element with the matching CSS selector will be returned. If no element has a matching CSS selector then as per usual a NoSuchElementException will be raised.

Below is an example of how to use this method
<html> <body>
  <p class="content">This is kevsbox.com</p>
</body><html>

In this example the “p” element can be located like this:
content = driver.find_element_by_css_selector('p. Content')



Browser Commands
In this section, we will discuss some of the browser commands which are available to you for use in your automated scripts. This is by no means a complete list but I am sure you will find these commands very useful in the future.
Get
The Get command is used to load a new web page in the current browser window, below are two examples of how this works.
Java
driver.get("http://www.kevsbox.com");
C#
driver.Navigate().GoToUrl("http://www.kevsbox.com");

GetTitle
The getTitle method fetches the Title of the current page. This method accepts nothing as a parameter and returns a String value, for example.

Java
String Title = driver.getTitle();
C#
String Title = driver.Title;

GetCurrentURL
The getCurrentURL method returns a string representing the Current URL which is opened in the browser, for example.
Java
String CurUrl = driver.getCurrentUrl();
C#
String CurUrl = Url;


GetPageSource
The getPageSource method returns the Source Code of the page, for example.
Java
String pSource = driver.getPageSource();
C#
String pSource = driver.PageSource;

Close
This method closes only the current window the WebDriver is currently controlling, for example.
Java
driver.close();
C#
driver.Close();


Quit
This method closes all windows opened by the WebDriver, for example.
Java
driver.quit();
C#
driver.Quit();

Switching windows
The GetWindowHandle Command is used to get the window handle of the current window. This command returns a string value, as per this example:
Java
String  handle= driver.getWindowHandle();
C#
String handle = driver.CurrentWindowHandle;

The GetWindowHandles Command is used to return the window handle of all the current windows. This command returns a set of strings, as per this example:
Java
Set<String> handle= driver.getWindowHandles();
C#
ReadOnlyCollection<string> handles = driver.WindowHandles;


The SwitchTo Window Command allows your test cases to move between named windows as per the example below:
Java
driver.switchTo().window("windowName");
C#
driver.SwitchTo().Window("windowName");