DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Playwright: Test Automation You Must Know
  • An Approach to Apply the Separation of Concern Principle in UI Test Automation
  • Windows Apps GUI Test Automation Using PyWinAuto
  • Modern Test Automation With AI (LLM) and Playwright MCP

Trending

  • Using Java Stream Gatherers To Improve Stateful Operations
  • Implementing API Design First in .NET for Efficient Development, Testing, and CI/CD
  • A Guide to Auto-Tagging and Lineage Tracking With OpenMetadata
  • Traditional Testing and RAGAS: A Hybrid Strategy for Evaluating AI Chatbots
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Selenium C# Tutorial: Using Implicit Wait in Selenium

Selenium C# Tutorial: Using Implicit Wait in Selenium

By 
Himanshu Sheth user avatar
Himanshu Sheth
DZone Core CORE ·
May. 22, 20 · Tutorial
Likes (12)
Comment
Save
Tweet
Share
11.6K Views

Join the DZone community and get the full member experience.

Join For Free

While designing test automation scripts, it is quite imperative that we consider all the major challenges that might come while performing Selenium test automation. There are certain scenarios where the test script is trying to perform an operation on an element that is not loaded (or not yet visible) and the test ends up failing due to this. This happens as the web elements on the page are loaded dynamically via AJAX (Asynchronous JavaScript and XML) and JavaScript or any other front-end framework.

To tackle this issue we have ‘Wait’, which is one of the most important and widely used commands in Selenium test automation. It helps us to provide us ample wait or pause time in our script execution. Thereby ensuring that our scripts don’t fail while performing automation testing with Selenium.

In this article we will talk about what are Selenium waits, why are they important, & how to implement an Implicit Wait in Selenium C# with examples.

What Are Waits In Selenium?

Selenium WebDriver is said to have a blocking API. It is an out-of-process library that instructs the web browser what exactly needs to be done. On the other hand, the web platform has an asynchronous nature. This is the primary reason why the Selenium WebDriver does not track the real-time state of the DOM (Document Object Model).

Race conditions could occur in a scenario where the developer uses a Selenium command to navigate to a particular URL (or web page) and gets a No Element Found error while trying to locate the element. To overcome such issues that can lead to race conditions between the web browser and the WebDriver script, the WebDriverWait class in Selenium C# can be used.

Waits in Selenium enable the test execution to be paused for a specified time (ideally in a few seconds) to address issues that can occur due to time lag. The added delay is a counter-mechanism to ensure that the particular web element is loaded before any action is performed on the element.

Why Are Selenium ‘Waits’ Important?

The front-end of most of the web applications are built on JavaScript or AJAX, using frameworks such as React, Angular, or others that take a certain time for the web elements to load entirely on the browser.

When Selenium comes across operations on web elements that are still loading, it throws the ElementNotVisibleException. Selenium waits can resolve such problems.

In the code snippet, the test scenario for our Selenium C# tutorial is for flight search on a flight booking website, which generates a ‘NoSuchElementException’ when the search operation is performed using Selenium test automation script.

C#
 




x
58


 
1
using NUnit.Framework;
2
using OpenQA.Selenium;
3
using OpenQA.Selenium.Chrome;
4
using OpenQA.Selenium.Firefox;
5
using OpenQA.Selenium.Support.UI;
6
using System;
7
 
8
namespace Selenium_Demo
9
{
10
    class Selenium_Demo
11
    {
12
        String test_url = "https://www.easemytrip.com";
13
 
14
        IWebDriver driver;
15
 
16
        [SetUp]
17
        public void start_Browser()
18
        {
19
            // Local Selenium WebDriver
20
            driver = new FirefoxDriver();
21
            driver.Manage().Window.Maximize();
22
        }
23
 
24
        [Test]
25
        public void test_search()
26
        {
27
            driver.Url = test_url;
28
 
29
            IWebElement from_sector = driver.FindElement(By.Id("FromSector_show"));
30
            from_sector.Click();
31
            /* from_sector.FindElement(By.XPath("//*[@id='spn2']")).Click(); */
32
            from_sector.FindElement(By.XPath("/html/body/form/div[10]/div/div[3]/div[1]/div[1]/div[1]/div[1]/div/div[2]/div/ul/li[1]")).Click();
33
 
34
            IWebElement to_sector = driver.FindElement(By.Id("Editbox13_show"));
35
            to_sector.Click();
36
            to_sector.FindElement(By.XPath("/html/body/form/div[10]/div/div[3]/div[1]/div[2]/div[1]/div/div/div/div/ul/li[2]")).Click();
37
 
38
            IWebElement ddate = driver.FindElement(By.Id("ddate"));
39
            ddate.Click();
40
 
41
            /* IWebElement snd_date = driver.FindElement(By.Id("snd_4_12/03/2020")); */
42
            IWebElement snd_date = driver.FindElement(By.Id("trd_3_18/03/2020"));
43
            snd_date.Click();
44
 
45
            IWebElement src_btn = driver.FindElement(By.ClassName("src_btn"));
46
            src_btn.Click();
47
 
48
            IWebElement booknow_btn = driver.FindElement(By.XPath("//button[text()='Book Now']"));
49
            booknow_btn.Click();
50
        }
51
 
52
        [TearDown]
53
        public void close_Browser()
54
        {
55
            driver.Quit();
56
        }
57
    }
58
}


As the page load is not complete i.e. the search for flights from source to destination is in progress, the script fails to find the ‘Book Now’ button. This results in the ‘NoSuchElementException’ for our Selenium test automation script. 

There are different types of waits in Selenium C# namely – Implicit wait, Explicit wait, and Fluent Wait. In this Selenium C# tutorial, we will have cover the Implicit wait in Selenium C#.

What Are Implicit Waits In Selenium C#?

Now moving ahead with our Selenium C# tutorial, Some developers use the System.Threading.Thread.Sleep(msecs) command to suspend the execution of the currently executing thread for a specified duration (specified in milliseconds). Usage of System.Threading.Thread.Sleep is considered to be a bad practice. The downside of this approach is that the Selenium WebDriver waits for irrespective of whether the web element is found or not. Usage of System.Threading.Thread.Sleep is considered to be a bad practice.

The shortcomings of the System.Threading.Thread.Sleep can be overcome using Implicit wait in Selenium C#. Implicit wait in Selenium halts the execution of the WebDriver for a specified duration of time until the desired web element is located on the page.

Unlike System.Threading.Thread.Sleep, the Implicit wait in Selenium does not wait for the complete time duration. Implicit wait in Selenium is also referred to as dynamic wait. If the particular web element is located before the expiry of the specified duration, it proceeds to execute the next line of code in the implementation.

If the particular web element is not located within the time duration, ElementNotVisibleException or NoSuchElementException is raised. Hence, implicit wait in Selenium tells the Selenium WebDriver to wait for a particular time duration (passed as a parameter), before the exception is raised.

The advantage of using implicit wait in Selenium C# is that it is applicable for all the web elements specified in the Selenium test automation script till the time WebDriver instance (or IWebDriver object) is alive.

Syntax of implicit wait in Selenium C#

C#
 




xxxxxxxxxx
1


 
1
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(time_in_seconds);


The default time value for the implicit wait is zero. Implicit wait polls for the presence of the web element every 500 milliseconds. Now to take our Selenium C# tutorial further, we move on to the features of implicit wait in Selenium test automation.

When To Use Implicit Wait In Selenium?

Though there are different types of Selenium waits (explicit wait and fluent wait), there are some key features that differentiate implicit wait in Selenium from other types of waits.

a. Implicit wait applies to all the web elements in the test script

b. It is ideal for test scenarios when we are sure that the web elements will be loaded (or visible) within a specified duration

Example of Implicit Wait in Selenium C#

To demonstrate implicit wait in Selenium C#, we take the same example of EaseMyTrip. The major difference is that we have added an implicit wait of 30 seconds.

C#
 




xxxxxxxxxx
1
79


 
1
using NUnit.Framework;
2
using OpenQA.Selenium;
3
using OpenQA.Selenium.Chrome;
4
using OpenQA.Selenium.Firefox;
5
using OpenQA.Selenium.Support.UI;
6
using System;
7
 
8
namespace Selenium_Demo
9
{
10
    class Selenium_Demo
11
    {
12
        String test_url = "https://www.easemytrip.com";
13
 
14
        IWebDriver driver;
15
 
16
        [SetUp]
17
        public void start_Browser()
18
        {
19
            // Local Selenium WebDriver
20
            driver = new ChromeDriver();
21
            driver.Manage().Window.Maximize();
22
        }
23
 
24
        [Test]
25
        public void test_search()
26
        {
27
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);
28
 
29
            driver.Url = test_url;
30
 
31
            IWebElement from_sector = driver.FindElement(By.Id("FromSector_show"));
32
            from_sector.Click();
33
            /* from_sector.FindElement(By.XPath("//*[@id='spn2']")).Click(); */
34
            from_sector.FindElement(By.XPath("/html/body/form/div[10]/div/div[3]/div[1]/div[1]/div[1]/div[1]/div/div[2]/div/ul/li[1]")).Click();
35
 
36
            IWebElement to_sector = driver.FindElement(By.Id("Editbox13_show"));
37
            to_sector.Click();
38
            to_sector.FindElement(By.XPath("/html/body/form/div[10]/div/div[3]/div[1]/div[2]/div[1]/div/div/div/div/ul/li[2]")).Click();
39
 
40
            IWebElement ddate = driver.FindElement(By.Id("ddate"));
41
            ddate.Click();
42
 
43
            /* IWebElement snd_date = driver.FindElement(By.Id("snd_4_12/03/2020")); */
44
            IWebElement snd_date = driver.FindElement(By.Id("trd_3_18/03/2020"));
45
            snd_date.Click();
46
 
47
            IWebElement src_btn = driver.FindElement(By.ClassName("src_btn"));
48
            src_btn.Click();
49
 
50
            IWebElement booknow_btn = driver.FindElement(By.XPath("//button[text()='Book Now']"));
51
            booknow_btn.Click();
52
 
53
            /* Next Steps for booking tickets */
54
            IWebElement insurance_checkbox = driver.FindElement(By.XPath("//div[@id='divInsuranceTab']//div[@class='insur-no']//span[@class='checkmark-radio']"));
55
            /* Click on NO INSURANCE */
56
            insurance_checkbox.Click();
57
 
58
            IWebElement email_entry = driver.FindElement(By.Name("txtEmailId"));
59
            email_entry.SendKeys("testing@gmail.com");
60
 
61
            driver.FindElement(By.XPath("//span[text()='Continue Booking']")).Click();
62
 
63
            IWebElement title = driver.FindElement(By.Id("titleAdult0"));
64
            SelectElement titleTraveller = new SelectElement(title);
65
 
66
            titleTraveller.SelectByText("MR");
67
            driver.FindElement(By.XPath("//input[@placeholder='Enter First Name']")).SendKeys("Himanshu");
68
            driver.FindElement(By.XPath("//input[@placeholder='Enter Last Name']")).SendKeys("Sheth");
69
            driver.FindElement(By.XPath("//input[@placeholder='Mobile Number']")).SendKeys("9031111111");
70
            driver.FindElement(By.XPath("//div[@class='con1']/span[@class='co1']")).Click();
71
        }
72
 
73
        [TearDown]
74
        public void close_Browser()
75
        {
76
            driver.Quit();
77
        }
78
    }
79
}


As an implicit wait is added, a wait of 30 seconds is added to locate the ‘Book Now’ button. 

C#
 




xxxxxxxxxx
1


 
1
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);


Due to this wait, the page load gets completed and we proceed with the flight ticket booking for our Selenium C# tutorial. 

Conclusion

In this Selenium C# tutorial, we had a look at why implicit wait in Selenium is necessary for Selenium test automation. The primary usage of Implicit wait in Selenium is to add a certain amount of delay of loading of the required web elements before an operation is performed on the element. Happy testing!

csharp Element Testing Test automation

Published at DZone with permission of Himanshu Sheth. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Playwright: Test Automation You Must Know
  • An Approach to Apply the Separation of Concern Principle in UI Test Automation
  • Windows Apps GUI Test Automation Using PyWinAuto
  • Modern Test Automation With AI (LLM) and Playwright MCP

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!