Automation Testing Interview Questions for Wait in Selenium C Sharp

In Selenium automation testing, one of the common challenges is managing waits effectively to ensure tests run reliably across different environments. Handling waits is a frequently asked topic in automation interviews, particularly for Selenium with C#. This guide explains the different types of waits, when to use them, and practical examples to help you ace such questions in interviews.

What Are Waits in Selenium?

Waits in Selenium are mechanisms to delay script execution until a certain condition is met or a specified time has elapsed. They are essential to account for varying application response times, ensuring stable and accurate test execution.

Types of Waits in Selenium C#

1. Implicit Wait in C#

An implicit wait tells Selenium to wait for a specified amount of time while locating elements before throwing a NoSuchElementException.

When to Use: For simple scenarios where the presence of elements is the only condition.

  • Applies globally to all element searches.
  • It is best for simple cases where all elements load predictably.
    driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
    
    

2. Explicit Wait in C#

An explicit wait allows you to wait for a specific condition to occur before proceeding. It is more flexible and precise than an implicit wait.

When to Use: When waiting for specific conditions, such as element visibility, clickability, or text presence.

Example: Waiting for an element to be visible

var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));

IWebElement element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Id("element-id")));

Example: Waiting for an element to be clickable

var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));

IWebElement element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.Id("element-id")));

3. Fluent Wait in C#

Fluent wait is an advanced form of explicit wait, allowing you to define the polling interval and ignore specific exceptions during the wait.

When to Use: When you need finer control over wait intervals and exceptions.

Fluent Wait allows you to define polling intervals and ignore specific exceptions.
Example: Waiting for an element with polling

DefaultWait<IWebDriver> fluentWait = new DefaultWait<IWebDriver>(driver)
{
Timeout = TimeSpan.FromSeconds(30),
PollingInterval = TimeSpan.FromSeconds(5)
};

// Specify exceptions to ignore
fluentWait.IgnoreExceptionTypes(typeof(NoSuchElementException));

// Wait for a specific condition
IWebElement element = fluentWait.Until(driver => driver.FindElement(By.Id("element-id")));

Common ExpectedConditions in C#

  • ExpectedConditions come from the SeleniumExtras.WaitHelpers namespace. Commonly used conditions include:
  • ElementExists(By locator)
  • ElementIsVisible(By locator)
  • ElementToBeClickable(By locator)
  • TextToBePresentInElementLocated(By locator, “text”)
  • AlertIsPresent()

Common Interview Questions on Waits

What is the difference between Implicit and Explicit Wait?

Implicit Wait applies globally to all elements in the WebDriver instance, while Explicit Wait applies to specific elements based on conditions.

What happens if Implicit and Explicit Wait are used together?

Selenium will wait for the longer duration of the two, which might lead to unnecessary delays.

Why should you avoid Thread.Sleep()?

Thread.Sleep() pauses execution for a fixed time, regardless of whether the condition is met, leading to inefficient test execution.
When should Fluent Wait be used?

When dealing with dynamic elements or conditions that may need retries at shorter intervals, while handling exceptions gracefully.

Best Practices for Handling Waits

  • Avoid overusing Thread.Sleep(); use implicit, explicit, or fluent waits instead.
  • Use Explicit Wait for scenarios with dynamic elements or conditions.
  • Keep wait durations reasonable to avoid unnecessarily long test runs.
  • Use Fluent Wait when exceptions like NoSuchElementException are common during retries.

Video Tutorial with Real Time Example

Complete Automation Script

Below is the source code that is used in the above video tutorial example.

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;
using SeleniumExtras.WaitHelpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpAutomation.CSharpBasic
{
    internal class AutomationTaskDemo
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello there");
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.next.co.uk/");
            driver.Manage().Window.Maximize();

            //Implicit wait: 10sec, element is found 2 sec
            //driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);



            //Explicit wait: 10sec: Not apply on all the elements.
            // Based on the condition, element is found 3 sec.
            var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));

            

          //Handle Cookies Popups
          driver.FindElement(By.XPath("//*[@id='onetrust-accept-btn-handler']")).Click();

            // Mouse Over
          IWebElement MenMenu =  driver.FindElement(By.XPath("//a[@title='MEN']"));
            Actions actions = new Actions(driver);
            actions.MoveToElement(MenMenu).Perform();


            wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//span[contains(text(),'Jeans')]")));
            driver.FindElement(By.XPath("//span[contains(text(),'Jeans')]")).Click();
    
            //find the list of reating test

                IList <IWebElement> ratingListEle = driver.FindElements(By.XPath("//span[@data-testid='product_summary_star-rating']"));

            foreach (IWebElement ratingElement in ratingListEle)
            {
                string ratingText = ratingElement.GetAttribute("title").ToString();
                // Split String

                var list = ratingText.Split(' ');

                double rating = Convert.ToDouble(list[list.Count()-2]);

                var productName = ratingText.Split('|');

                String finalProjectName = productName[0];

                Console.WriteLine(finalProjectName+ " : "+ rating);

            }

            //driver.Quit();

        }

       
    }
}