Getting Started with Selenium Test Automation using C#

Have you ever felt frustrated with the amount of tedious and repetitive testing you have to do every time a new feature gets added or something breaks in your complex web application? As a fellow QA professional with over 10+ years of experience automating tests on real devices, I have been there!

The problem is exponential with increasing project timelines and code changes. As our dev team started adopting CI/CD pipelines and adopting agile methodology, our reliance on automation also grew exponentially. We knew there is no keeping up without intelligent use of tools and frameworks for continuous testing.

In my journey so far, I have had the opportunity to work on automating 3500+ test cases spread across various complex enterprise websites and mobile applications using open source tools like Selenium and Appium as well as commercial tools.

Let me tell you this – Selenium WebDriver is by far the most widely used UI automation tool allowing you to write tests across browsers and operating systems. And when combined with C# language binding, you can build scalable automation framework for reliable and maintainable tests.

Through this comprehensive hands-on guide, I will share my decade long experience in helping software teams setup test automation practice using Selenium with C#.

Here is brief overview of what we will cover:

Section 1: Selenium Webdriver Introduction

  • What is Selenium?
  • Why is it most popular automation tool?
  • Selenium components
  • Supported languages

Section 2: Advantages of C# with Selenium

  • Why use C# for test automation?
  • Key features and benefits
  • .NET ecosystem support

Section 3: Setup Guide

  • Install Visual Studio
  • Create new Selenium C# project
  • Configure WebDriver dependencies
  • Setup Chrome and Firefox drivers

Section 4: First Selenium C# Test

  • Write sample test
  • Execute test on Chrome browser
  • Analyze test results

Section 5: Best Practices

  • Page object model
  • Reuse utilities and configs
  • Parameterization and external data
  • Reporting
  • Exception handling
  • Dynamic waits

Section 6: Integrations

  • Run with CI/CD pipelines
  • Achieve cross browser testing
  • Cloud based Selenium grids

I will also share code snippets and examples throughout this guide to help you practice the concepts.

Shall we get started?

Section 1: Introduction to Selenium

Let‘s first understand what is Selenium, why is it so popular and how does it work.

What is Selenium?

Selenium is an open-source test automation tool for web applications across different browsers and platforms. It allows you to write code to simulate user interactions like click, type text etc. to automate navigating web pages as well as asserting page content.

Key Reasons for Popularity

Here are some key reasons why Selenium is most widely used by automation engineers:

  • Open source and easy to get started
  • Supports multiple languages like Java, C#, Python etc.
  • Runs on Windows, Mac, Linux environments
  • Allows testing on all popular browsers like Chrome, Firefox and Safari
  • Integrates with tools like Git, Jenkins, Docker etc.
  • Scalable distributed testing on Selenium grid

Selenium Components

Selenium has the following components:

  • Selenium WebDriver – This is the core library that enables automating browser based testing. Includes bindings for languages like Java, C#, Python etc.
  • Selenium IDE – This adds recording and playback capability without needing to code through Firefox/Chrome plugin.
  • Selenium Grid – Grid allows distributed test execution scalability by running tests across multiple machines.

Supported Languages

You can use Selenium WebDriver with following languages:

  • Java
  • C#
  • Python
  • JavaScript
  • Ruby
  • PHP

In this guide, we will use C# programming language.

Section 2: Advantages of C# with Selenium

C# is modern, powerful and most importantly easy to learn – making it a great choice to build test automation frameworks.

Let‘s look at some of the key advantages:

Easy to learn

C# has simplified C++ constructs making it familiar for Java developers. Clear and concise syntax helps you focus on problem solving.

Rich Programming Constructs

C# provides a comprehensive object oriented feature set – classes, interfaces, inheritance, generics etc. This helps model test suite‘s logical components efficiently.

Microsoft Ecosystem

Seamless integration with Visual Studio IDE for .NET developers. Can leverage tools like Intellisense, robust debugger, rich UI controls etc.

Open and Flexible

C# programs are executed on Cross Platform .NET runtime allowing Windows, Linux and Mac support. You have flexibility to build web, mobile and desktop applications.

Access to .NET Libraries

As part of .NET ecosystem, C# allows leveraging the expansive set of inbuilt libraries for security, data access, workflow, AI amongst thousands of others accelerating test framework creation.

Community Support

Given Microsoft‘s backing and developer goodwill, C# has one of the largest support community in forums like StackOverflow helping resolve issues faster.

I hope you now have better clarity on why C# is preferred for test automation and how it complements Selenium so well.

Now let us move on to the next section of setting up the test project.

Section 3: Selenium C# Test Project Setup

We will use Visual Studio community edition to setup our framework comprising of:

  1. Install Visual Studio
  2. Create new C# project
  3. Setup Selenium references
  4. Configure browser drivers

Step 1: Install Visual Studio

Visual Studio provides a feature rich IDE for rapid .NET application development.

  1. Download the Visual Studio community here.
  2. Choose the Installer and follow prompts to complete setup. This may take some time.
  3. On Workloads screen, select .NET desktop development module.
  4. Complete the install process.

Step 2: Create New Project

Let‘s create a Selenium project with NUnit test framework.

  1. Open Visual Studio > Click File > New > Project
  2. Select NUnit Test Project (.NET Core)
  3. Enter project name like SeleniumCSharpDemo
  4. Click Create

This will setup a basic test project including NUnit test adapter references! That was quick 🙂

Step 3: Setup Selenium References

We now need to add Selenium WebDriver bindings through NuGet package manager.

  1. Click Tools > Manage NuGet Packages
  2. Search Selenium WebDriver
  3. Select package by Selenium contributors and click Install
  4. Similarly install Selenium.Support package

You will now see Selenium libraries added to the project references automatically.

Step 4: Configure Browser Drivers

The tests require a browser driver executable placed locally to execute scripts.

  1. Create a Drivers folder in Solution Explorer
  2. Download ChromeDriver and place in folder
  3. For Firefox, download GeckoDriver

Awesome! Our Selenium project with C# is now ready to start test coding. Exciting times ahead!

Section 4: Our First Selenium C# Test

We have setup the framework, so its now time to write our first Selenium test in C#.

Let‘s start with something very basic – navigate to google.com and assert page title.

Test Step 1 – Launch Chrome browser using ChromeDriver

IWebDriver driver = new ChromeDriver(@".\Drivers\");

Test Step 2 – Open URL google.com

driver.Navigate().GoToUrl("https://www.google.com");  

Test Step 3 – Assert page title contains Google

Assert.That(driver.Title, Does.Contain("Google"));

Test Step 4 – Close browser

driver.Quit();

Let‘s combine above steps into our first Selenium C# test:

[Test]
public void GoogleSearchTest() {

  IWebDriver driver = new ChromeDriver(@".\Drivers\");

  driver.Navigate().GoToUrl("https://www.google.com");

  Assert.That(driver.Title, Does.Contain("Google"));

  driver.Quit();

}   

Executing First Test

  1. Open Test Explorer in Visual Studio
  2. Click Run All to execute test
  3. Test passes if title has Google!

Awesome! We have created and run our first Selenium C# test. Let‘s extend this further following some best practices.

Section 5: Best Practices for Automated Testing

Now that you have learned how to create Selenium scripts with C#, let‘s focus on some of the key best practices which separate the good frameworks from the great ones!

Use Page Object Model

Page Object Model or POM is a design pattern to create object repository for web elements. It is considered one of the most popular patterns to build maintainable test automation frameworks.

For example:

public class LoginPage {

  IWebDriver driver;  

  public LoginPage(IWebDriver driver) 
  {
    this.driver = driver;
  }

  By usernameLocator = By.Id("username");

  public void EnterUsername(string username)
  {
    driver.FindElement(usernameLocator).SendKeys(username); 
  }

}

And in your test class:

var login = new LoginPage(driver);

login.EnterUsername("JohnWick");

Reuse Common Utilities

Common helpers for tasks like taking screenshots, JavaScript execution, database validations can all be built once and reused across various test classes.

public class SeleniumUtils 
{
    public static void HighlightElement(IWebDriver driver, IWebElement element)
        {
            /* JavaScript to highlight element */
        }  
}

//Test class 
SeleniumUtils.HighlightElement(driver, loginButton);

Parameterize Tests

Same tests can run across different data using NUnit features like testcasesource, datarow etc. This improves test coverage without needing more scripts.

@TestCaseSource("data")

public void LoginTest(String user, String pass)
{
  LoginPage login = new LoginPage();

  login.EnterUsername(user); 
  login.EnterPassword(pass);

  login.ClickLogin();  
}

static object[] data = new object[]{
  new object[] {"user1","pass1"}, 
  new object[] {"user2","pass2"}
};

Implement Custom Reporting

NUnit provides basic reporting but rich interactive reports can be generated using frameworks like ExtentReports and Report Portal.

Exception Handling

Use try catch blocks at both test and method level for stable test execution. This allows catching errors gracefully without breaking test suite.

Manage Waits and Timeouts

Selenium provides both implicit and explicit waits to handle page load and ajax activity delays:

Implicit Wait

driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

Explicit Wait

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

wait.Until(ExpectedConditions.ElementToBeClickable(loginButton)); 

loginButton.Click();

This makes script reliable across varying systems.

These were some of the key best practices to create professional automation frameworks.

Now let‘s understand adding capabilities like cross browser testing and CI/CD integration.

Section 6: Integrations for Automation Framework

Let‘s now discuss how the test framework can be enhanced using capabilities like parallel execution, integration with developer workflows and cross browser cloud grids.

Run with CI/CD Pipelines

The test suite can be easily plugged into CI/CD pipelines creating a devops culture with automation at the center.

      Code > Build > Test > Release

Tools like Azure Devops, TeamCity, Jenkins can trigger Selenium scripts.

Achieve Cross Browser Testing

Running same tests across browsers is essential for web app quality. Local executions can be setup by just updating the driver object.

//Chrome
IWebDriver driver = new ChromeDriver();

//Firefox           
IWebDriver driver = new FirefoxDriver();

However, testing across dozens of browser, OS and resolution combinations is challenging to scale.

Leverage Cloud Selenium Grids

Cloud based grids allow accessing thousands of browser/OS on demand enabling comprehensive test coverage without infrastructure costs.

These solutions leverage container technology and auto-scaling to offer true parallel testing capability.

For example LambdaTest Selenium Grid offers 2000+ real desktop and mobile browsers running on their highly optimized cloud infrastructure. You get additional capabilities like:

  • Cross platform support with Windows, Linux and MacOS
  • One click Bug reporting and project management
  • Historical Results mapping
  • Performance analytics
  • Integrations with CI/CD and project management tools

This enables extreme scale and flexibility in executing Selenium scripts without needing to spend weeks in infrastructure setup and maintenance.

Final Thoughts

This brings us to the end of our detailed guide on using Selenium and C# for automated testing.

I hope the practical walkthrough has equipped you to setup and extend test automation framework following leading practices. You are now ready to start evaluating use cases applicable for your project needs and augment overall quality culture.

Feel free to reach out to me in comments below if you have any additional questions as you adopt test automation in your teams.

Happy Testing!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Similar Posts