Learn Selenium with C# in this tutorial. Discover how to automate web testing, navigate pages, interact with elements, and validate results step by step.
OVERVIEW
Selenium is one of the most preferred frameworks for web automation testing and supports languages like C#, Java, JavaScript, Python, Ruby, and PHP. Using Selenium C# for test automation offers two main benefits: seamless integration with development projects and better collaboration on improving the testing framework.
In this tutorial, we will look at how to perform automated testing using Selenium C#, covering best practices and real-world examples.
C# ( or C-Sharp) is an object-oriented language that runs on the .NET framework. It works with the Common Language Runtime (CLR). In C#, software applications can be split into smaller components using functions. This makes C# a structured programming language.
It is chosen for Selenium testing because it's a modern, statically typed, object-oriented language with easy-to-read syntax, which simplifies writing and maintaining tests. It provides a wide array of features for automation and comes with a rich set of libraries and frameworks, such as NUnit. These resources support testing across different types of applications, including desktop, web, mobile, and games.
Subscribe to the LambdaTest YouTube Channel LambdaTest YouTube Channel for more such tutorials on Selenium C#.
Before you get started, you need to have a code editor installed on your machine. For this Selenium C# tutorial, let’s use Visual Studio. However, you can use any IDE of your choice.
You can also check out this blog to set up Selenium in Visual Studio.
Follow the below steps to create a new project in Selenium with C#:
If you want to see and run the tests in the Visual Studio, you need to follow the below steps:
Note : Run C# automated tests with Selenium at scale. Try LambdaTest Now!
The following are the prerequisites to run tests on the local grid:
To add a NuGet package to the project, please follow the below-mentioned steps:
Alternatively, you can install NuGet packages from the command line by running this command in the project location:
dotnet add package Selenium.WebDriver --version 4.22.0
One thing to make sure of here is to install the same driver version as the browser you have installed on your machine.
You can use the browser of your choice, and you can add the drivers the same way, for example, Selenium.WebDriver.MSEdgeDriver (for Microsoft Edge), Selenium.WebDriver.GeckoDriver (for Mozilla Firefox).
For the test scenario, let’s use the LambdaTest Selenium Playground.
Test Scenario:
|
Test Implementation:
Now, we should be ready to start our Selenium C# test. Let’s use the previously created class and rename it to SeleniumTests.
public class SeleniumTests
{ private IWebDriver driver;
[SetUp]
public void Setup()
{
driver = new ChromeDriver();
}
[Test]
public void ValidateTheMessageIsDisplayed()
{
driver.Navigate().GoToUrl("https://www.lambdatest.com/selenium-playground/simple-form-demo");
driver.FindElement(By.Id("user-message")).SendKeys("LambdaTest rules");
driver.FindElement(By.Id("showInput")).Click();
Assert.IsTrue(driver.FindElement(By.Id("message")).Text.Equals("LambdaTest rules"),
"The expected message was not displayed.");
}
[TearDown]
public void TearDown()
{
driver.Quit();
}
}
}
Code Walkthrough:
Import packages at the beginning of the test class. Then, create a new instance of the IWebDriver.
As a precondition to the test, start the browser. For this tutorial, it is done using the [SetUp] method because it’s something that will be used in all future tests, so here is where the driver is instantiated.
Next, there is our actual test, where the previously mentioned [Test] attribute from NUnit is used, and inside the test method, the test steps.
To navigate to a URL in Selenium with C#, use the Navigate().GoToUrl() method. When you need to interact with page elements, you can locate them using the FindElement() method, and it's best to go with the ID locator since it’s quicker.
After that, you can enter text using the SendKeys() method, click buttons using the Click() method, and check if everything worked as expected using Assert.IsTrue() method, adding a custom message for easier debugging if something goes wrong.
To close the browser at the end of the test, use the [TearDown] attribute and the quit() method.
Test Execution:
Now that the test is ready, you can build the project (right-click on the project name and select Build or use the Ctrl+B shortcut) and run the test locally. The test will be visible in the Test Explorer:
If everything goes well, the test will pass, and the browser window will close at the end.
What if you want to run the automated tests cross-platform or cross-browser? Or using a setup different from your own machine? These situations likely happen often because we want our web applications to work for all our users, and they will have various configurations set up on their computers.
The solution for this is porting the existing Selenium C# tests to a cloud-based Selenium Grid like LambdaTest. AI-driven unified test execution platforms like LambdaTest provide an online Selenium Grid of 3000+ browsers and operating systems to perform Selenium C# testing at scale.
The best part is that not much porting effort is involved in porting the existing tests from the local Selenium Grid to the LambdaTest cloud grid. To run our tests on the cloud, let’s use the same test scenario of the Simple Form Demo page of the Selenium Playground.
Test Implementation:
Here’s the version of the test script configured to run the tests on the LambdaTest cloud grid.
private static IWebDriver driver;
public static string gridURL = "@hub.lambdatest.com/wd/hub";
public static string LT_USERNAME = "LT_USERNAME"; // Add your LambdaTest username here
public static string LT_ACCESS_KEY = "LT_ACCESS_KEY"; // Add your LambdaTest access key here
[SetUp]
public void Setup()
{
ChromeOptions capabilities = new ChromeOptions();
capabilities.BrowserVersion = "126";
Dictionary<string, object> ltOptions = new Dictionary<string, object>();
ltOptions.Add("username", LT_USERNAME);
ltOptions.Add("accessKey", LT_ACCESS_KEY);
ltOptions.Add("platformName", "Windows 10");
ltOptions.Add("project", "SeleniumTutorial");
ltOptions.Add("build", "Selenium CSharp");
ltOptions.Add("w3c", true);
ltOptions.Add("plugin", "c#-nunit");
capabilities.AddAdditionalOption("LT:Options", ltOptions);
driver = new RemoteWebDriver(new Uri($"https://{LT_USERNAME}:{LT_ACCESS_KEY}{gridURL}"), capabilities);
}
Code Walkthrough:
When using LambdaTest, you need to make sure you use your Username and Access Key. You can find them by going to your Account Settings > Password & Security.
A good idea is to store them as environment variables and read them from there. This way, in case any of the values change, you only need to update them in one place.
The biggest change, as you can see, is in the [Setup] method. ChromeOptions is a Selenium class used to configure browser attributes for cross browser testing using Chrome.
You can use the LambdaTest Automation Capabilities Generator to create your automation capabilities to run the tests.
The remaining test script will remain unchanged.
Test Execution:
Now run the test, the same as before, from Visual Studio. This time, the browser will not open locally. Instead, you will see the test execution in the LambdaTest Web Automation Dashboard.
Here are some best practices for Selenium C# testing:
Using Selenium with C# can be a great choice if you are just getting started with test automation. In this Selenium C# tutorial, we covered the main steps for getting started with a test automation project, from selecting the testing framework to identifying the WebElements, interacting with them, and adding validations.
If you are a developer or a tester and want to master the fundamentals of Selenium automation testing with C#, you can take the Selenium C# 101 certification by LambdaTest to prove your credibility as a tester.
Did you find this page helpful?
Try LambdaTest Now !!
Get 100 minutes of automation test minutes FREE!!