Saturday 15 March 2014

How to add synchronization using selenium webdriver in C#.Net

When you automate the test cases using Selenium webdriver, you will have to add synchronization points because page elements may take different time to load depending upon the network speed.
There are mainly 2 things to consider.

  1. Page load is taking too long
  2. Some section of the page is loading asynchronously using ajax. In this case, even if the page is loaded, elements from the specific section of the page loading with ajax may take different times.
To handle these situations selenium webdriver provides 2 kinds of Waits.
  1. Implicit Waits
  2. Explicit Waits
1. Implicit Waits in Selenium Webdriver in C#.Net

We can specify the page load time out using below line of code. Remember that implicit waits are one time settings and work for until driver session exists. 

driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(50));

We can specify the element existence time out using below line of code.
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

2. Explicit Waits in Selenium Webdriver in C#.Net

We can use explicit waits to wait for specific condition on the element. Below code will wait for the element with id - dd to come into existence.

It will ignore the 2 exceptions - StaleElementReferenceException, InvalidElementStateException

WebDriverWait w = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
           w.IgnoreExceptionTypes(typeof(StaleElementReferenceException),typeof(InvalidElementStateException));

w.Until(ExpectedConditions.ElementExists(By.Id("dd")));

Other expected conditions are mentioned below. 

  1. ElementIsVisible - wait until element becomes visible
  2. TitleContains      - wait until title contains given substring
  3. TitleIs         - wait until title matches given string


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

No comments:

Post a Comment

Buy Best Selenium Books

Contributors