Synchronizing web driver and Ignoring Exceptions in C# Selenium API

In general the website response times may cause issues while doing the UI automation testing. Most of the times test scripts will fail due to synchronizations issues from web-driver and the application web elements.

Following are the common reasons and if we see very frequent issues in synchronization it is suggested to do performance testing and tuning.

  • Location from where we are accessing the application (Latency)
  • Network bandwidth
  • Too much firewall checks
  • Website architecture and technology on which website built on.

Most of these cases are taken care while doing performance tuning and performance engineering, but yet we see page load issues, element enabling issues and visibility issues while doing UI automation.

In selenium we have several methods that we can use to make sure that these things are taken care. Following is the just enough explanation about waits in Selenium driver.

Implicit waits will wait until the defined action (example page loading ) is complete.

Example of it is managed time outs, and they are defined at driver level.

Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);
Driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(30);

When we want to wait explicitly at certain number of seconds we will use explicit waits. As the name suggests the test execution will be halted during this time. Example of it is sleep

 Thread.Sleep(2000);

here the parameter indicates the number of milliseconds to wait for.

The other case of waiting for dynamic web elements is using wait until or web driver waits. These are most common implicit waits that are used. There are two ways we can use these.

We can declare the web driver wait and and it will wait for max wait in this case it is 30 seconds, and repeatedly we can check for the expected conditions i this case we are looking for visibility of the element google search text box.

IWebElement textbox;
WebDriverWait waits = new WebDriverWait(Driver, TimeSpan.FromSeconds(30));
textbox = waits.Until(SeleniumExtras
.WaitHelpers
.ExpectedConditions
.ElementIsVisible((By.Name(SEARCH_TEXT_BOX_NAME))));

There is another way we can use this as function delegate, following is how it is used.

//there is another way using function delegate
//delegate parameters and return value = new delegate parameters return value of passed parameters
//delegate is on the fly function generator
Func<IWebDriver,IWebElement>checkForvisibilityOfWebElement = new Func<IWebDriver, IWebElement>((IWebDriver Driver) =>
  {
     IWebElement textBoxDelegate = Driver.FindElement(By.Name(SEARCH_TEXT_BOX_NAME));
       if (textBoxDelegate.Displayed)
           return textBoxDelegate;
       else
          return null;
   }); 
 
 textbox = waits.Until(checkForvisibilityOfWebElement);

When you look at above code, its function delegate takes one argument as IWebDriver and returns the IWebElement. The last argument of function delegate is always a return type.

The wait until function will take this and checks for the condition mentioned in the delegate periodically.

If you look at the until you can clearly see this text.

WaitUntill

But if we look closely, the description says it will throw exception if it is not listed in the Ignore Exception list.

For that purpose. We have to configure our waits object what exceptions that we want to ignore while we periodically check for our condition. We can achieve this by following.

IWebElement textbox;
WebDriverWait waits = new WebDriverWait(Driver, TimeSpan.FromSeconds(30));

waits.IgnoreExceptionTypes(typeof(NoSuchElementException));
waits.IgnoreExceptionTypes(typeof(ElementNotSelectableException));

There are list of exceptions that we may want to ignore, following is the snap shot.

ExceptionList

And finally following is the list of element states we can wait for.

ListOfwaitsfor

Please comment if you see anything is incorrect or you want to add something you know. Thank you.

 

Advertisement

Design Selenium Framework with C# – Part 5

Now since we have created the basic framework and page classes. Lets look at NUnit framework to create tests.

NUnit 3.0 supports parallel testing, and prior to that it supports the testing multiple iterations with different parameters.

Here if you see TestFixture attribute allows the test class to take the constructor parameter. I.E parameters you are defining in the testfixture will be passed to constructor of the test class if matching definition is found. This is very useful when we need to execute same tests with different browsers, we can define BrowserType to achieve the same purpose. The test class will be initiated and tests will be executed for each of those test fixtures.

Also Prallalizable (ParllelScope.Self) will run the test methods in parallel. More information can be found in below link.  Nunit documentation

If you look at the below code, constructor of the test class has browsertype as parameter which is matching with the parameter defined the test fixture. So the test class will run for each browser type.

NUnitTestFixure

And the SetUp attribute is similar to TestSetup in MSTest framework or BeforeTest in TestNG. This will sets up the preconditions for each test.

If you look at the test execution flow

  • Starts at calling DriverFactory.InitDriver(browserType)
  • This will invoke and create corresponding BrowserDriver class object
  • Driver property will be set in the DriverFactory Class with the type of the driver
  • Using the DriverFactory.GetDriver() method we are getting driver to the thread which has initiated it.
  • It will be passed to the Page Classes to do the rest of the test flow.DriverGet

If you look at the test explorer it identifies the tests based on the TestFixture types.

TestExplorer

When you click on run it will run all tests in parallel. You can see the results in the test explorer for each iteration Results

IterationResults

This is the simplest explanation I could give quickly for the Selenium with C# implementation with interface design pattern.

I have not touched any Reporting/Logging part for the framework.

As It can be implemented with ILogger interface with different logging methods so that each logging type (Excel logging, Text, Word/pdf, html) can be implemented easily.

Having said this, it will conclude our discussion on creating the framework.

Please feel free to follow and write to me if you need help in understanding any of these items.

Design Selenium Framework with C# – Part 1

In the current Selenium space there are lot of developments are happening. One of the most asked questions in the internet is how to design extensible and most easy frame work that can be suited for different kinds of testing platforms such as desktop, mobile.

Selenium with C# is not that common in the current freeware market era. But its worth knowing about how it can be implemented so that we can future ready. C# is now becoming language for building all kinds of apps including mobile. Having knowledge on C# selenium will bring us more opportunities for a devops engineer.

With that preface, I will try to create a logical flow of learning. Lets look at following areas one by one to achieve our goal of learning.

I typically go with bare minimum requirements to create the framework assuming readers know the basics of any object oriented programming language. So I am starting with concepts familiar but implemented little different in C#.

  • Basics of C# interfaces and setters and getters.
  • Basics of Interface design pattern for framework creation.
  • MS visual studio nuget packages required and drivers required for selenium
  • Driver factory or thread safe driver creation
  • NUnit testing framework bare minimum to Create basic google search test with Nunit

In this blog lets start with first section.

C# provides the important feature of setting and getting the class properties. There are auto properties which are really useful and takes care of the coding.

Setters sets the properties and getter will get you the properties. Following is the example of setters and getters. This is widely used and need to be understood while working with C#

public class test
{
private string _anyproperty;
public string AnyProperty
{
get{return _anyproperty;}
set{ _anyproperty = value;}
}
}

In the above example we can declare private variable and use it to assign and return. This is same as setting auto properties like below in C#.

public class test
{
public string AnyProperty
{
get;set;
}
}

Class properties can be set inside class or out side the class using the class object.
The properties are quite useful in designing the framework. Usually anything we want to set for the entire class such as file path for the excel operations class, file path for the browser driver class etc, this same path can be used in the class methods.

In the next section we will see how interfaces can be used to create portable and readable code.

Interface is generally known as contract agreement. It signs the contract with implementing classes. I.E it enforces the method definitions for implementing class.

The underlying code can differ with different class implementations.

In view of our selenium, let’s take the example of Browser driver, the IWebDriver interface holds the method definitions and all driver classes such as ChromeDriver, FireFoxDriver , IEDriver classes implements the methods in IWebDriver interface.

To understand how we can make use of interfaces to create clean code while designing the C# frame work, lets look at browser object creation.

In C# selenium browser object can be initialized similar to Java. To initialize browser object we need two objects

  • Browser Service
  • Browser Options or Capabilities.
    • IWebDriver ChromeDriver = new ChromeDriver ((ChromeDriverService)service, (ChromeOpions)capabilities, timeout)
    • IWebDriver FireFoxDriver = new FireFox ((FireFoxDriverService)service, (FireFoxOpions)capabilities, timeout)
    • IWebDriver InternetExplorerDriver = new InternetExplorerDriver((InternetExplorerDriverService)service, (InternetExplorerOptions)options, timeout)

If we look at all three initialization, in fact all driver classes implementing IWebDriver have these three parameters two of which are class objects.

It makes sense for us to utilize the interface concept here and create IDriver interface which have two methods (Service object creation and capabilities/option object creation)

This will enforce for all types of driver objects to implement these methods.

Lets end the first part here, and in the next part, will dive deep and create framework using MS visual studio.

Design Selenium Framework with C# – Part 2