Saturday, May 6, 2017

How to use implicit wait in selenium webdriver | David Tzemach

Selenium WebDriver provides us the capability to implement an implicit wait command that we can use for synchronizing the test execution with the available elements. 

When we set an Implicit wait in our code, we will provide a safe net to the WebDriver API in any case that the element is not immediately available in the Object Model (DOM), now he will wait for the element to appear in the DOM based on the Implicit wait that was set in the Timeouts ().ImplicitlyWait (time to wait) method.

תוצאת תמונה עבור ‪selenium webdriver‬‏

Furthermore:
  • An implicit wait can be set with different time frames (Hours, Minutes, Seconds Etc.).
  • Once set, the implicit wait is applied for the entire life of the WebDriver instance.
  • The implicit wait is declared with a single line (Usually on the setup function).
  • By design, the default delay value of implicit wait is 0 seconds.
  • It is not suggested to use the implicit wait a large time counter (And to be more productive, make sure that you minimize the use of this method).
  • When used, the implicit wait may slow down the test execution because it will wait for each element appearing in the DOM.
  • Implicit wait can be changed numerous time (No Limitation) thought the session of the IWebDriver.
  • The default polling time is 250 milliseconds (means that WebDriver will search the element in DOM after every 250 milliseconds until he found it or the time specified is ended).
In the following code snippet, we will explore some basic ways for using the implicit wait.

[TestMethod]
public void ImplicitWait ()
{
//Creating a new WebDriver instance
IWebDriver Firefox = new FirefoxDriver();

//StreamWriter sw = new StreamWriter(@"Location to save the file", true);
StreamWriter sw = new StreamWriter (@"Log location", true);

//Navigate to a web page
Firefox.Navigate().GoToUrl("http://www.machtested.com");

//Set a new implicit wait time of 15 seconds
Firefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(15));

try
{
//Locate a page element that does not exist
IWebElement WebElement = Firefox.FindElement(By.XPath("//a[.='Not Exists']"));

//Validation
Assert.AreEqual("Quality Assurance", WebElement.Text);
}
catch (NoSuchElementException ex)
{
//Print the Error
sw.WriteLine(ex.Message);

//Print the Stack Trace
sw.WriteLine(ex.StackTrace);

//optional if you want to mark the test as "Failed" or "Pass"
Assert.Fail();
}
finally{Firefox.Close();}
}

No comments:

Post a Comment

My Presentations