Selenium C# Tutorial: NUnit Framework with Example

⚡ Smart Summary

Selenium WebDriver drives browsers from C# through the IWebDriver interface, while NUnit supplies the test attributes, assertions and Test Explorer reporting that turn those browser steps into repeatable automated tests.

  • 🔘 Toolchain: Visual Studio plus the Selenium WebDriver, NUnit and NUnit Test Adapter NuGet packages.
  • ☑️ Project setup: Output type must be Class Library, not Console Application, or the build fails.
  • NUnit attributes: SetUp opens the browser, Test performs the actions, TearDown closes it.
  • 🧪 Command groups: browser commands, WebElement commands and dropdown commands via SelectElement.
  • 🛠️ Locators: FindElement accepts XPath and CSS selector strategies for every element interaction.
  • Execution: Test Explorer runs the class and reports each result as passed or failed.

Selenium C# automation with the NUnit test framework

Selenium Overview

Selenium is an open-source, web Automation Testing tool that supports multiple browsers and multiple operating systems. It allows testers to use multiple programming languages such as Java, C#, Python, Ruby, PHP and Perl for coding automated tests. If you are new to the tool, start with the Selenium tutorial and the WebDriver versus Selenium RC comparison.

Selenium supplies the browser control; the language you drive it with supplies the structure.

C# Overview

C# is an object-oriented programming language derived from C++ and Java. C# allows developers to build applications using Visual Studio on .NET platform. The following are the key features of C#.

  1. It is an Object-Oriented programming language
  2. It supports the development of console, windows and web-based applications
  3. It provides features such as Encapsulation, Inheritance, and Polymorphism.

Before wiring Selenium in, it helps to recognise the shape of a plain C# program.

Basic Syntax of C#

A program in C# needs to contain the following sections

  1. Namespace declaration
  2. Classes
  3. Class Attributes and Methods
  4. Main method
  5. Program statements

Example-

Below is a sample Selenium C# example program to print the text ‘Guru99’ on the system console.

using System;
namespace FirstProgram {
class DemoPrint {
static void main(){
    Console.WriteLine("Guru99");
	}
  }
}

Explanation:

  • A namespace in the above Selenium C# example is a collection of multiple classes. Each namespace must be declared using the keyword ‘using’.
  • The first statement of the code includes the namespace ‘System’ into our program. System namespace defines the fundamental classes and events used in C#. The namespace to be used depends on the program requirement.
  • The second statement is declaring a namespace “FirstProgram” for the class “DemoPrint.” A C# file can contain multiple classes within the same namespace.
  • The third statement includes the class declaration. A class may contain multiple attributes and multiple methods.
  • The fourth statement includes a declaration of the Main method. The main method is the entry point of execution for each class.
  • The last statement is the C# syntax used for printing a statement to console. WriteLine is a method of the Console class. Note that the entry point is spelled Main with a capital M in real C#; the lowercase main in the sample above will not be recognised as an entry point.

With the syntax clear, the next job is installing the tooling that compiles and runs those tests.

Selenium with C# Setup

How to Set Up Visual Studio with Selenium WebDriver:

Now in this Selenium C# tutorial, let’s learn the step by step process to set up Visual Studio with Selenium WebDriver:

Visual Studio is an Integrated Development Environment (IDE) that is used by developers to build applications across multiple platforms such as Windows, Android, iOS and Cloud-based applications.

Step 1) Navigate to the URL

https://visualstudio.microsoft.com/downloads/ and Click on the ‘Free download’ button displayed on Visual Studio Community tab

Visual Studio Downloads page with the Community edition Free download button

Step 2) Open the exe downloaded. Click on ‘Yes’ if asked for Admin Rights.

Visual Studio installer asking for administrator rights

Step 3) The below popup will appear. Click on ‘Continue’ button.

Visual Studio installer welcome popup with the Continue button

Files will be downloaded as shown in the popup below.

Visual Studio installer downloading the component files

Step 4) In the next screen,

Select the checkboxes for

  • Universal Windows Platform development
  • .NET desktop development

Click on ‘Install.’

Visual Studio workload screen with Universal Windows Platform and .NET desktop development ticked

Wait for installation of each component to complete. Files are 16GB in size and will take time.

Visual Studio installer progress bar for each selected component

Step 5) The below pop up will be displayed. Click on ‘Restart’ button.

Visual Studio installer prompting for a machine restart

Step 6) Once the machine is restarted, search for “Visual Studio” on the start menu and click on the search result. The following popup will appear. Click on “Not now, maybe later” link if you do not have an existing account.

Visual Studio sign-in popup with the Not now, maybe later link

Step 7) In the next screen,

  • Select color theme of your liking
  • Click the button “Start Visual Studio’”

Visual Studio first-launch screen for choosing a colour theme

Step 8) Visual Studio ‘Get Started’ screen will appear.

Visual Studio Get Started screen after installation completes

Create a new project in Visual Studio:

Step 1) In the File Menu, Click New > Project

Visual Studio File menu with New and Project selected

Step 2) In the next screen,

  1. Select the option ‘Visual C#’
  2. Click on Console App (.Net Framework)
  3. Enter name as “Guru99”
  4. Click OK

New Project dialog with Visual C# Console App and the project named Guru99

Step 3) The below screen will be displayed once the project is successfully created.

Visual Studio editor showing the newly created Guru99 console project

Set up Visual Studio with Selenium WebDriver:

Step 1) Navigate to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution

Tools menu path to NuGet Package Manager and Manage NuGet Packages for Solution

Step 2) In the next screen

  1. Search for Selenium on the resultant screen
  2. Select the first search result
  3. Check the project checkbox
  4. Click on ‘Install’

NuGet package manager with the Selenium search result and project checkbox ticked

Step 3) Click on ‘OK’ button in the pop-up screen

NuGet confirmation popup before the Selenium package is installed

Step 4) The below message will be displayed once the package is successfully installed.

NuGet output confirming Selenium WebDriver installed successfully

Selenium can now open a browser, but it cannot yet report whether a test passed. That is the job of a unit testing framework.

NUnit Framework: Overview

NUnit is the Unit Testing framework supported by Visual Studio and Selenium WebDriver. NUnit is the most widely used Unit Testing framework for .NET applications. NUnit presents the test results in a readable format and allows a tester to debug the automated tests.

We need to install NUnit Framework and NUnit Test Adapter onto Visual Studio in order to use it.

Steps to install NUnit Framework

Now in this Selenium with C# tutorial, let’s learn the process to install NUnit framework:

Step 1) Navigate to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution

Tools menu reopened at NuGet Package Manager for the NUnit installation

Step 2) In the next window

  1. Search for NUnit
  2. Select the search result
  3. Select Project
  4. Click Install

NuGet package manager with the NUnit search result selected for install

Step 3) The below popup will appear. Click on ‘Ok’ button.

NuGet confirmation popup before the NUnit framework is installed

Step 4) The below message will appear once the installation is complete.

NuGet message confirming the NUnit framework installation finished

Steps to download NUnit Test Adapter

Now in this NUnit tutorial, we will cover the steps to download NUnit Test Adapter:

Please note that the below steps work only for 32-bit machines. For 64-bit machines, you need to download the ‘NUnit3 Test Adapter’ by following the same process as mentioned below.

Current packages: a modern project installs NUnit3TestAdapter together with Microsoft.NET.Test.Sdk, and the older NUnitTestAdapter package is no longer maintained. On .NET (Core) the whole project can be scaffolded with dotnet new nunit, which adds all three packages for you.

Step 1) Navigate to Tools ->NuGet Package Manager -> Manage NuGet Packages for Solution. In that screen,

  1. Search NUnitTestAdapter
  2. Click Search Result
  3. Select Project
  4. Click Install

NuGet package manager searching for NUnitTestAdapter with the project selected

Step 2) Click OK on the confirmation pop-up. Once install is done you will see the following message-

NuGet message confirming the NUnit Test Adapter installation finished

Both halves are installed, so the next step is joining them in a single test class.

Selenium and NUnit framework

Integration of selenium with NUnit framework allows a tester to differentiate between various test classes. NUnit also allows testers to use annotations such as SetUp, Test, and TearDown to perform actions before and after running the test.

NUnit framework can be integrated with Selenium by creating a NUnit test class and running the test class using NUnit framework. The Java equivalent of this pattern is covered in the JUnit framework tutorial, and the .NET alternative to NUnit inside Visual Studio is discussed alongside TestNG for Selenium.

Below steps in this Selenium C# framework tutorial are needed to create and run a test class using NUnit framework.

Steps to create a NUnit Test class in Selenium:

Step 1) In the Solution Explorer, right-click the project > Add > Class

Solution Explorer context menu with Add and Class selected

Step 2) Class creation window will appear.

  1. Provide a name to the class
  2. Click on Add button

Add New Item dialog used to name the new NUnit test class

Step 3) The below screen will appear.

Empty C# class file created in the Visual Studio editor

Step 4) Add the following code to the created class. Please note that you need to specify the location of ‘chromedriver.exe’ file during chrome driver initialization. Selenium 4.6 and later ship Selenium Manager, which resolves the matching driver automatically, so new ChromeDriver() with no path argument is the current form — the path below is kept because it matches the screenshots.

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Guru99Demo
{
	class Guru99Demo						
    {
        IWebDriver driver;

        [SetUp]
		public void startBrowser()
        {
            driver = new ChromeDriver("D:\\3rdparty\\chrome");
        }

        [Test]
		public void test()
        {
            driver.Url = "http://www.google.co.in";
        }

        [TearDown]
		public void closeBrowser()
        {
            driver.Close();
        }

    }
}

Step 4) Click on ‘Build’ -> ‘Build Solution’

Build menu with Build Solution selected in Visual Studio

NOTE: You may get an error like “Does not contain a static ‘main’ method suitable for an entry point” when you build

Build error reporting no static main method suitable for an entry point

To resolve this, go to Project > Properties and change Output Type to “Class Library.” The default is “Console Application.”

Project properties with Output type switched to Class Library

Step 5) Once the build is successful, we need to open the Test Explorer window. Click on Test -> Windows -> Test Explorer

Test menu path to Windows and Test Explorer

Step 6) Test Explorer window opens with the list of available tests. Right-click on Test Explorer and select Run Selected Tests

Test Explorer listing the available test with Run Selected Tests

Step 7) Selenium must open the browser with specified URL and close the browser. Test case status will be changed to ‘Pass’ on the Test Explorer window.

Test Explorer showing the NUnit test result marked as passed

A passing test proves the plumbing works. What follows is the vocabulary you will actually write tests with.

Selenium WebDriver Commands in C#

C# uses the interface ‘IWebDriver’ for browser interactions. The following are the category of commands available with Selenium in C#.

  1. Browser commands
  2. Web Element commands
  3. Dropdown commands

Now in this Selenium C# tutorial, let us study the Selenium WebDriver commands one by one. The Java counterparts are demonstrated in this first WebDriver script walkthrough.

The commands below are still the current IWebDriver surface in Selenium 4, so the syntax carries over unchanged.

Browser commands:

Following is a list of browser commands available in C# with Selenium.

Command Name Description Syntax
Url Command This command is used to open a specified URL in the browser.
driver.Url = "https://www.guru99.com"
Title Command This command is used to retrieve the page title of the web page that is currently open
String title = driver.Title
PageSource Command This command is used to retrieve the source code of web page that is currently open.
String pageSource = driver.PageSource
Close Command This command is used to close the recently opened browser instance.
driver.Close();
Quit Command This command is used to close all open browser instances
driver.Quit();
Back Command This command is used to navigate to the previous page of browser history.
driver.Navigate().Back();
Forward Command This command is used to navigate to the next page of browser history.
driver.Navigate().Forward()
Refresh Command This command is used to perform browser refresh.
driver.Navigate().Refresh()

Browser commands act on the window; the next group acts on what is inside it.

WebElement Commands

A WebElement represents any element on a web page. They are represented by HTML tags. Buttons, text boxes, links, images, tables and frames are all WebElements. Operations on those elements are triggered through the IWebElement interface. To interact with a WebElement, we first find the element on the page and then perform an operation on it. The available strategies are covered in locators in Selenium. Browser developer tools — or the legacy Firebug and Firepath add-ons the screenshots below predate — can be used to identify the XPath of a WebElement.

The following are the WebElement commands available in C#.

Command Name Description Syntax
Click command This command is used to click on a Webelement. For the element to be clickable, the element must be visible on the webpage. This command is used for checkbox and radio button operations as well.
IWebelement element = driver.FindElement(By.xpath("xpath of Webelement"));  element.Click();
Clear command This command is specifically used for clearing the existing contents of textboxes.
IWebelement element = driver.FindElement(By.xpath("xpath of Webelement")); 
element.Clear();
SendKeys command This command is used to input a value onto text boxes. The value to be entered must be passed as a parameter to
IWebelement element = driver.FindElement(By.xpath("xpath of Webelement")); 
element.SendKeys("guru99");
Displayed command This command is used to identify if a specific element is displayed on the webpage. This command returns a Boolean value; true or false depending on the visibility of web element.
IWebelement element = driver.FindElement(By.xpath("xpath of Webelement")); 
Boolean status = element.Displayed;
Enabled command This command is used to identify if a particular web element is enabled on the web page. This command returns a Boolean value; true or false as a result.
IWebelement element = driver.FindElement(By.xpath("xpath of Webelement")); 
Boolean status = element.Enabled;
Selected command This command is used to identify if a particular web element is selected. This command is used for checkboxes, radio buttons and select operations.
IWebelement element = driver.FindElement(By.xpath("xpath of Webelement")); 
Boolean status = element.Selected;
Submit command: This command is similar to click command, The difference lies in whether the HTML form has a button with the type Submit. While the click command clicks on any button, submit command clicks on the only the buttons with type submit.
IWebelement element = driver.FindElement(By.xpath("xpath of Webelement"));  element.submit();
Text command This command returns the innertext of a Webelement. This command returns a string value as a result.
IWebelement element = driver.FindElement(By.xpath("xpath of Webelement")); 
String text=element.Text;
TagName command This command returns the HTML tag of a web element. It returns a string value as the result.
IWebelement element = driver.FindElement(By.xpath("xpath of Webelement"));  String tagName = element.TagName;
GetCSSValue Command: This method is used to return the color of a web element on the form of a rgba string (Red,Green,Blue, and Alpha).
IWebelement element = driver.FindElement(By.xpath("xpath of Webelement")); 
String color = element.getCSSValue;

Output– If the color of element is red, output would be rgba(255,0,0,1)

Note on the samples above: the table reproduces the original syntax. In current Selenium .NET the members are Pascal-cased — element.Submit() and element.GetCssValue("color") — and GetCssValue takes the CSS property name as an argument.

Dropdown Commands:

Dropdown operations in C# can be achieved using the SelectElement class.

The following are the various dropdown operations available in C#.

Command Name Description Syntax
SelectByText Command This command selects an option of a dropdown based on the text of the option.
IWebelement element = driver.FindElement(By.xpath("xpath of Webelement")); 
SelectElement select = new SelectElement(element);
select.SelectByText("Guru99");
SelectByIndex Command This command is used to select an option based on its index. Index of dropdown starts at 0.
IWebelement element = driver.FindElement(By.xpath("xpath of Webelement")); 
SelectElement select = new SelectElement(element);
select.SelectByIndex("4");
SelectByValue Command This command is used to select an option based on its option value.
IWebelement element = driver.FindElement(By.xpath("xpath of Webelement")); 
SelectElement select = new SelectElement(element);
select.SelectByValue("Guru99");
Options Command This command is used to retrieve the list of options displayed in a dropdown.
IWebelement element = driver.FindElement(By.xpath("xpath of Webelement")); 
SelectElement select = new SelectElement(element);
List<IWebelement> options = select. Options;
int size = options.Count;
for(int i=0;i<options.size();i++)
{
String value = size.elementAt(i).Text;
Console.writeLine(value);
}

The above code prints all the options onto console within a dropdown.

IsMultiple command This command is used to identify if a dropdown is a multi select dropdown; A multi-select dropdown lets the user choose more than one option at a time. This command returns a Boolean value.
IWebelement element = driver.FindElement(By.xpath("xpath of Webelement")); 
SelectElement select = new SelectElement(element);
Boolean status = select.IsMultiple();
DeSelectAll command This command is used in multi select dropdowns. It clears the options that have already been selected.
IWebelement element = driver.FindElement(By.xpath("xpath of Webelement")); 
SelectElement select = new SelectElement(element);
select.DeSelectAll();
DeSelectByIndex command This command deselects an already selected value using its index.
IWebelement element = driver.FindElement(By.xpath("xpath of Webelement")); 
SelectElement select = new SelectElement(element);
select.DeSelectByIndex("4");
DeSelectByValue command This command deselects an already selected value using its value.
IWebelement element = driver.FindElement(By.xpath("xpath of Webelement")); 
SelectElement select = new SelectElement(element);
select.DeSelectByValue("Guru99");
DeSelectByText command This command deselects an already selected value using its text.
IWebelement element = driver.FindElement(By.xpath("xpath of Webelement")); 
SelectElement select = new SelectElement(element);
select.DeSelectByText("Guru99");

The four scripts below put the commands above to work against the Guru99 demo site. Each one is a complete, runnable NUnit test class.

Code Samples

Example 1: Click on a link using XPATH Locator:

Test Scenario:

  1. Navigate to Demo Guru99 web page – https://demo.guru99.com/test/guru99home/
  2. Maximize the window
  3. Click on the ‘Testing’ menu
  4. Close the browser
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Guru99Demo
{
	class CSS						
    {
        IWebDriver m_driver;

        [Test]
		public void cssDemo()
        {
            m_driver = new ChromeDriver("D:\\3rdparty\\chrome");
            m_driver.Url = "https://demo.guru99.com/test/guru99home/";
            m_driver.Manage().Window.Maximize();
            IWebelement link = m_driver.FindElement(By.XPath(".//*[@id='rt-header']//div[2]/div/ul/li[2]/a"));
            link.Click();
            m_driver.Close();
        }
    }
}

Example 2: Entering data into TextBox and Click on a button using XPATH locator:

Test Scenario:

  1. Navigate to the Guru99 demo page – https://demo.guru99.com/test/guru99home/
  2. Enter data into email text box
  3. Click on sign up button
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Guru99Demo
{
	class CSS						
    {
        IWebDriver m_driver;

        [Test]
		public void cssDemo()
        {
            m_driver = new ChromeDriver("G:\\");
            m_driver.Url = "https://demo.guru99.com/test/guru99home/";
            m_driver.Manage().Window.Maximize();

             
			// Store locator values of email text box and sign up button				
            IWebElement emailTextBox = m_driver.FindElement(By.XPath(".//*[@id='philadelphia-field-email']"));
            IWebElement signUpButton = m_driver.FindElement(By.XPath(".//*[@id='philadelphia-field-submit']"));

            emailTextBox.SendKeys("test123@gmail.com");
            signUpButton.Click();
                        
        }
    }
}			

Example 3: Entering data into TextBox and Click on a button using CSS locator:

Test Scenario:

  1. Navigate to the Guru99 demo page – https://demo.guru99.com/test/guru99home/
  2. Enter data into email text box
  3. Click on sign up button
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Guru99Demo
{
	class CSS						
    {
        IWebDriver m_driver;

        [Test]
		public void cssDemo()
        {
            m_driver = new ChromeDriver("G:\\");
            m_driver.Url = "https://demo.guru99.com/test/guru99home/";
            m_driver.Manage().Window.Maximize();

             
			// Store locator values of email text box and sign up button				
            IWebElement emailTextBox = m_driver.FindElement(By.CssSelector("input[id=philadelphia-field-email]"));
            IWebElement signUpButton = m_driver.FindElement(By.CssSelector("input[id=philadelphia-field-submit]"));

            emailTextBox.SendKeys("test123@gmail.com");
            signUpButton.Click();

             
        }
    }
}

Example 4: Select a value in the dropdown:

Test Scenario:

  1. Navigate to the Guru99 demo page – https://demo.guru99.com/test/guru99home/
  2. Click on SAP link
  3. Enter data onto name and email text boxes
  4. Select a value from the Course dropdown
  5. Close the browser
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;


namespace Guru99Demo
{
	class TestSelect						
    {
        IWebDriver m_driver;

        [Test]
		public void selectDemo()
        {
            m_driver = new ChromeDriver("G:\\");
            m_driver.Url = "https://demo.guru99.com/test/guru99home/";
            m_driver.Manage().Window.Maximize();

            IWebElement course = m_driver.FindElement(By.XPath(".//*[@id='awf_field-91977689']"));

			var selectTest = new SelectElement(course);
			// Select a value from the dropdown				
            selectTest.SelectByValue("sap-abap");
                        
        }
    }
}

FAQs

Use Selenium.WebDriver 4.x with NUnit 3.14 or NUnit 4, plus NUnit3TestAdapter and Microsoft.NET.Test.Sdk. NUnit 4 targets .NET Framework 4.6.2 or .NET 6 and later, so check your project target before upgrading from the packages shown above.

No. Selenium 4.6 introduced Selenium Manager, which downloads and matches the browser driver at runtime. Passing a driver folder to the ChromeDriver constructor still works, but it is only needed when you must pin a specific driver build.

An implicit wait applies a single timeout to every element lookup for the life of the IWebDriver instance. An explicit wait targets one element and one condition, such as clickable or visible, so it fails faster and describes the intent more precisely.

Yes. Mark the assembly with Parallelizable and NUnit runs fixtures concurrently. Each test must own its IWebDriver instance, so create the driver in SetUp rather than sharing a static field, otherwise parallel tests collide on the same browser.

NUnit and MSTest both use attributes and group tests with TestFixture or TestClass. xUnit needs no class attribute and was designed around parallelism. All three run in Test Explorer; NUnit remains the most common choice for Selenium work in C#.

AI tooling proposes locators from a page snapshot, repairs selectors that broke after a UI change, and converts a written test case into a draft NUnit method. Treat every suggestion as a draft and review the assertions before committing.

Yes. Given a comment describing the scenario, Copilot drafts the SetUp, Test and TearDown members and suggests FindElement calls from surrounding code. Verify the locators against the live page, because generated selectors are inferred rather than inspected.

Selenium has the widest grid, cloud and language support and a very large existing test estate, so the skill stays employable. Playwright offers faster execution and built-in waiting. Many .NET teams run both, sharing the same NUnit runner and reports.

Summarize this post with: