How to use Selenium in C#?


We can use Selenium in C#. We should have Visual Studio 2019 installed in the system along with Selenium webdriver and any browser like Firefox, Chrome, and so on. Then we must utilize the NUnit framework.

Launch Visual Studio 2019 and then click on Create a new project.

Type NUnit in the search box appearing in Create a new project pop−up. Select NUnit Test Project(.NET Core) from the search results.

Enter Project name and Location. Then click on Create to proceed.

As the project is set up on NUnit(.Net Core), the Setup and Test methods shall be given by default.

We should navigate to the Tools menu, select NuGet Package Manager, and then click on Package Manager Console.

We must execute the required Package Manager commands for installation of Selenium webdriver and NUnit.

For Selenium installation for Firefox, run the below commands in Package Manager Console −

Install−Package Selenium.WebDriver
Install−Package Selenium.Firefox.WebDriver

For Selenium installation for Chrome, run the below commands in Package Manager Console −

Install−Package Selenium.WebDriver
Install−Package Selenium.Chrome.WebDriver

For NUnit installation, run the below commands in Package Manager Console −

Install−Package NUnit
Install−Package UUnit3TestAdapter

To check the installation status, run the command in Package Manager Console −

Get−Package

Example

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;
namespace NUnitTestProject1{
   public class Tests{
      String u = "https://www.tutorialspoint.com/index.htm";
      IWebDriver d;
      [SetUp]
      public void Setup(){
         //creating object of FirefoxDriver
         d = new FirefoxDriver();
      }
      [Test]
      public void Test1(){
         //launching URL
         d.Navigate().GoToUrl(u);
         Console.WriteLine("Url launched");
      }
      [TearDown]
      public void close_Browser(){
         d.Quit();
      }
   }
}

Go to Build, then select Build Solution.

Go to Test−>Test Explorer. Then run the tests. The output in Test Explorer is −

Click on Open additional output for this result link, we should get the Test Outcome and Standard Output.

Updated on: 30-Jan-2021

439 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements