Skip to main content

C# with Selenium: Run C# Automation Testing Scripts on LambdaTest Selenium Grid


LambdaTest Selenium Automation Grid is a cloud-based scalable Selenium testing platform that enables you to run your automation scripts on 2000+ different browsers and operating systems. You can now run your C# automation testing test cases on a scalable Selenium infrastructure that is running real browsers and real operating systems.

This post will help you start configuring and running your C# automation testing scripts on LambdaTest Selenium cloud platform. In this post, we would be exploring:

  1. How to run a C# and Selenium script on LambdaTest Selenium Cloud.
  2. How to specify which browsers to run C# Automation Testing on.
  3. How to run your test cases in parallel to reduce build times.
  4. How to test your locally hosted pages.
  5. How to leverage LambdaTest’s Advanced capabilities.

Prerequisites For Running C# With Selenium#


All the code samples in this documentation can be found in the C# LambdaTest Repository on git GitHub. You can either download or clone the repository to quickly run your tests.

Before you begin C# automation testing with Selenium, be ready with the below essentials:

  • Make sure you work with the latest version of C#.
  • Download and Install [Selenium WebDriver(https://www.lambdatest.com/blog/selenium-webdriver-tutorial-with-examples/)] from the official website.
  • .Net framework to deliver guidelines while developing a range of application using C#.
  • Download Selenium WebDriver Language Bindings for C# and extract them to the appropriate folder.
  • Although it isn’t necessary, it is always recommended to use a test automation framework. You can use NUnit for C#.
  • You would also need a LambdaTest tunnel binary file for testing your locally hosted or privately hosted projects.

Getting Started Using C# With Selenium#


The first step in using the LambdaTest platform is to understand LambdaTest’s Selenium Grid capabilities. Our Selenium Grid uses remote WebDriver instead of normal Selenium client browser drivers. If you are migrating from locally run Selenium, you would have to invoke LambdaTest Selenium remote WebDriver. Next, you need to specify in your code, which browser, browser versions, operating systems, and resolution you wish to run your test on, along with defining LambdaTest specific capabilities. You can check out LambdaTest Capabilities Generator tool to understand more about how you can define running browser environments and leverage advanced LambdaTest capabilities.

Let us begin with a simple Selenium Remote WebDriver test first. The C# automation testing script below tests a simple to-do application with basic functionalities like mark items as done, add items in a list, calculate total pending items, etc. You can also find this at GitHub.

using NUnit.Framework;using OpenQA.Selenium;using OpenQA.Selenium.Remote;using System;using System.Configuration; namespace LambdaTestCSharp{   public class Program    {        private static IWebDriver driver;        private static String ltUserName;        private static String ltAppKey;        private static String platform;        private static String browser;        private static String browserVersion;        static void Main(string[] args)        {            InitCaps();            DesiredCapabilities caps1 = new DesiredCapabilities();            caps1.SetCapability("platform", platform);            caps1.SetCapability("browserName", browser); // name of your browser            caps1.SetCapability("version", browserVersion); // version of your selected browser            caps1.SetCapability("name", "CSharpTestSample");            caps1.SetCapability("build", "LambdaTestSampleApp");            caps1.SetCapability("user", ltUserName);            caps1.SetCapability("accessKey", ltAppKey);            Console.WriteLine(ConfigurationSettings.AppSettings["LTUrl"]);             driver = new RemoteWebDriver(new Uri(ConfigurationSettings.AppSettings["LTUrl"]), caps1, TimeSpan.FromSeconds(600));            driver.Manage().Window.Maximize();            driver.Url = "https://lambdatest.github.io/sample-todo-app/";             Assert.AreEqual("Sample page - lambdatest.com", driver.Title);            String itemName = "Yey, Let's add it to list";            // Click on First Check box            IWebElement firstCheckBox = driver.FindElement(By.Name("li1"));            firstCheckBox.Click();             // Click on Second Check box            IWebElement secondCheckBox = driver.FindElement(By.Name("li2"));            secondCheckBox.Click();             // Enter Item name             IWebElement textfield = driver.FindElement(By.Id("sampletodotext"));            textfield.SendKeys(itemName);             // Click on Add button            IWebElement addButton = driver.FindElement(By.Id("addbutton"));            addButton.Click();             // Verified Added Item name            IWebElement itemtext = driver.FindElement(By.XPath("/html/body/div/div/div/ul/li[6]/span"));            String getText = itemtext.Text;            Assert.IsTrue(itemName.Contains(getText));             driver.quit(); //really important statement for preventing your test execution from a timeout.        }        public static void InitCaps()         {            if (String.IsNullOrEmpty(Environment.GetEnvironmentVariable("LT_USERNAME")))            {                ltUserName = ConfigurationSettings.AppSettings["LTUser"];            }            if (String.IsNullOrEmpty(Environment.GetEnvironmentVariable("LT_APPKEY")))                 ltAppKey = ConfigurationSettings.AppSettings["LTAccessKey"];             if (String.IsNullOrEmpty(Environment.GetEnvironmentVariable("LT_OPERATING_SYSTEM")))                 platform = ConfigurationSettings.AppSettings["OS"];             if (String.IsNullOrEmpty(Environment.GetEnvironmentVariable("LT_BROWSER")))                 browser = ConfigurationSettings.AppSettings["Browser"];             if (String.IsNullOrEmpty(Environment.GetEnvironmentVariable("LT_BROWSER_VERSION")))                 browserVersion = ConfigurationSettings.AppSettings["BrowserVersion"];        }    }}

Here is App.config file which is used for setting application settings in C# automation testing.

<?xml version="1.0" encoding="utf-8" ?><configuration>    <startup>        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />    </startup>    <appSettings>      <add key="URL" value="https://lambdatest.github.io/sample-todo-app/" />      <add key="LTUser" value= "">      <add key="LTAccessKey" value="" />      <add key="LTUrl" value="https://hub.lambdatest.com/wd/hub" />            <add key="Browser" value="chrome" />       <add key="BrowserVersion" value="62.0" />       <add key="OS" value="win10" />    </appSettings>   </configuration>

The Selenium Webdriver test would open a URL, mark the first two items in the list as done, add an item in the list, and return the total number of pending items. Your results would be displayed on the test console (or command-line interface if you are using terminal/cmd) and on the LambdaTest dashboard. LambdaTest Dashboard will help you view all your text logs, screenshots and video recording for your entire Selenium tests.

Execute The Test Using C# With Selenium#


You would need to execute the below command in your terminal/cmd.

COMMAND REQUIRED

Understanding & Configuring C# Desired Capabilities#


As we said earlier, the first step is to configure your test scripts to connect with LambdaTest Selenium automation grid. In the above mentioned C# code, the first thing you would notice is invoking remote WebDriver instead of the native browser WebDrivers. So, for example if you are planning to run on Firefox browser on your local machine, you would be using Firefox browser driver like this:

IWebDriver driver = new FirefoxDriver();

However, to run on the LambdaTest Selenium grid, you would have to change its remote webdriver and at the same time pass capabilities related to the browser, browser versions, etc. In simple terms, it would look something like this:

IWebDriver driver= new RemoteWebDriver(new URL(https://hub.lambdatest.com/wd/hub), caps1, TimeSpan.FromSeconds(600));

In the C# code, we are passing browser, browser version, and operating system information, along with LambdaTest Selenium grid capabilities via capabilities object.

Our Capabilities Generator will automatically generate the program, based on your provided input. For Instance, if you select the below configurations:

CapabilitySelected Value
Operating SystemMacOS High Sierra
Resolution1280×1024
BrowserMozilla Firefox
Browser Version64.0
Selenium Version3.13.0

Then Capabilities Generator at LambdaTest will provide you with the below program:

DesiredCapabilities capabilities = new DesiredCapabilities();capabilities.SetCapability("build", "your build name");capabilities.SetCapability("name", "your test name");capabilities.SetCapability("platform", "macOS High Sierra"); // Selected Operating systemcapabilities.SetCapability("browserName", "Firefox"); // Name of your selected browser.capabilities.SetCapability("version","64.0"); // Selected Browser Versioncapabilities.SetCapability("resolution","1280x1024"); // Screen resolution of your VM(Virtual Machine).capabilities.SetCapability("selenium_version","3.13.0"); // Selenium versioncapabilities.SetCapability("visual",true);capabilities.SetCapability("firefox.driver",v0.23.0);

The most important capabilities to understand here are ‘browserName’, ‘versions’, and ‘platform’. They define which browser environment you wish to run the test on. Rest of the capabilities are important in test management and debugging. We have a an inbuilt capabilities generator tool as well that you use to generate capabilities code for your test suite.

You can also check out our documentation on capabilities generator to understand more about individual capabilities.

Advanced LambdaTest Capabilities#


In addition to default Selenium Grid capabilities, LambdaTest also has platform specific capabilities like video recording of test runs, console logs of each test run, network logs of each test run, custom profiles for specific browsers, etc. Do check out our documentation on LambdaTest Advanced capabilities as well.

Testing Locally Hosted or Privately Hosted Websites Using C# With Selenium#


To help you perform cross browser testing of your locally stored web pages, LambdaTest provides an SSH(Secure Shell) tunnel connection with the name LambdaTest tunnel. With LambdaTest tunnel, you can test your locally hosted files before making them live over the internet. You could even perform cross browser testing from different IP addresses belonging to various geographic locations. You can also use LambdaTest Tunnel to test web-apps and websites that are permissible inside your corporate firewall. The SSH tunnel provided by LambdaTest acts as a proxy server for hosting your web pages from your local machine to Virtual machines running on LambdaTest cloud servers. Curious to know more about LambdaTest tunnel?

Follow our documentation on LambdaTest tunnel to know it all. OS-specific instructions to download and setup tunnel binary can be found at the following links.


Download the binary file of:

You can start tunnel by executing the below command in your cmd(Command Prompt) / terminal. Make sure that your pointer is routed in the same directory where you extract the downloaded LambdaTest tunnel zip file.

//Syntax To Start LambdaTest tunnel
LT --user [user's login email] --key [user's access key]

For example, if your user login email is [email protected] and your user key is 123asd123, then the command would be:

//Example Command To Start LambdaTest tunnel
LT --user [email protected].com --key 123asd123

Once the tunnel is successfully set up. You can add the below code to your capabilities for testing internal servers on your network.

//Tunnel Capabilities
DesiredCapabilities capabilities = new DesiredCapabilities();        capabilities.SetCapability("tunnel", true);

You can also add the capability using LambdaTest Capabilities Generator.

Tunnel Reference: For a full reference of all tunnel features we offer at LambdaTest, visit our tunnel page.

Mark Tests As Pass Or Fail#


While performing automation testing using C# with Selenium on the LambdaTest Selenium grid, it is imperative to flag an automation test as either pass or fails. This is completely dependent on your testing requirement with respect to the validation of expected behavior. You can mark whether an automation test passed or failed by adding the below code fragment in your automation script:

((IJavaScriptExecutor)driver.Value).ExecuteScript("lambda-status=" + (passed ? "passed" : "failed"));

Parallel Testing Using C# with Selenium#


Parallel Testing is one of the most demanding features of LambdaTest Selenium Grid. By parallel testing, you can run more than one test case, simultaneously. This means that Parallel testing would allow you to execute numerous automation test cases altogether. So you execute a single test scenario across different browsers or could run different test scenarios across the same browser but with different browser versions. Wondering how many parallel test cases can you run? That depends entirely on the number of concurrent sessions under your opted plan.

For instance, if you have a bucket of 100 automated test cases, and the average time for execution of a single test is around 6 minutes. The time taken normally to completely execute all your test cases sequentially would be 600 minutes, i.e., 10 hours. However, if you are opting for a plan which offers 2 concurrent sessions then you can perform 2 parallel test cases. This would divide your time in half as the total time taken through parallel testing with 2 concurrent sessions for the above scenario would be 300 minutes, i.e. 5 hours. Similarly, if you have got 4 concurrent sessions with you then the time taken would be a quarter with respect to sequential testing. This way, you could fasten your release cycles as much as you want.

Test automation frameworks like NUnit are really useful in running parallel tests. For instance, in our above example, you may notice that we are running our test in a single environment. If you want to cover multiple environments, you would have to change the hard code every time. Or you would have to use arrays, or multi-threading, or something similar.

With LambdaTest, you can pace up your test build activities by performing parallel automation testing using C# with Selenium and NUnit. Boost quality assurance of your product by conducting extensive and fast-paced automated cross browser testing process with LambdaTest parallel testing.

Checkout the same code below to understand it better. You can also find it at our github page here.

Parallel Testing Example#


using OpenQA.Selenium;using OpenQA.Selenium.Remote;using NUnit.Framework;using ParallelSelenium.Utils;using System.Threading;using System.Collections.Generic; namespace ParallelLTSelenium{    [TestFixture("chrome", "67.0", "Windows 10")]    [TestFixture("internet explorer", "11.0", "Windows 7")]    [TestFixture("firefox", "41.0", "Windows 7")]    [TestFixture("chrome", "30.0", "Windows 7")]    [TestFixture("internet explorer", "9.0", "Windows 7")]    [TestFixture("firefox", "30.0", "Windows 7")]    [TestFixture("chrome", "38.0", "Windows 7")]    [TestFixture("internet explorer", "10.0", "Windows 7")]    [TestFixture("firefox", "35.0", "Windows 7")]    [Parallelizable(ParallelScope.Children)]    public class ParallelLTTests    {         ThreadLocal<IWebDriver> driver = new ThreadLocal<IWebDriver>();        private String browser;        private String version;        private String os;         public ParallelLTTests(String browser, String version, String os)        {            this.browser = browser;            this.version = version;            this.os = os;        }         [SetUp]        public void Init()        {            String seleniumUri = "http://{0}:{1}/wd/hub";            DesiredCapabilities capabilities = new DesiredCapabilities();            capabilities.SetCapability(CapabilityType.BrowserName, browser);            capabilities.SetCapability(CapabilityType.Version, version);            capabilities.SetCapability(CapabilityType.Platform, os);            //Requires if you want to test internal web app.            if (Constants.tunnel != false)            {                capabilities.SetCapability("tunnel", Constants.tunnel);            }            if (Constants.build != null)            {                capabilities.SetCapability("build", Constants.build);            }                if (Constants.seleniumPort != null && Constants.seleniumHost != null)            {              seleniumUri = String.Format(seleniumUri, Constants.seleniumHost, Constants.seleniumPort);            }            capabilities.SetCapability("user", Constants.Username);            capabilities.SetCapability("accessKey", Constants.Accesskey);            capabilities.SetCapability("name",               String.Format("{0}:{1}: [{2}]",               TestContext.CurrentContext.Test.ClassName,               TestContext.CurrentContext.Test.MethodName,               TestContext.CurrentContext.Test.Properties.Get("Description")));            driver.Value = new RemoteWebDriver(new Uri(seleniumUri), capabilities, TimeSpan.FromSeconds(600));                         driver.Value.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));        }         [Test]        public void Todotest()        {            {            driver.Url = "https://lambdatest.github.io/sample-todo-app/";             Assert.AreEqual("Sample page - lambdatest.com", driver.Title);                         String itemName = "Yey, Let's add it to list";            // Click on First Check box            IWebElement firstCheckBox = driver.FindElement(By.Name("li1"));            firstCheckBox.Click();             // Click on Second Check box            IWebElement secondCheckBox = driver.FindElement(By.Name("li2"));            secondCheckBox.Click();             // Enter Item name             IWebElement textfield = driver.FindElement(By.Id("sampletodotext"));            textfield.SendKeys(itemName);             // Click on Add button            IWebElement addButton = driver.FindElement(By.Id("addbutton"));            addButton.Click();             // Verified Added Item name            IWebElement itemtext = driver.FindElement(By.XPath("/html/body/div/div/div/ul/li[6]/span"));            String getText = itemtext.Text;            Assert.IsTrue(itemName.Contains(getText));                             }        }         [TearDown]        public void Cleanup()        {            bool passed = TestContext.CurrentContext.Result.Outcome.Status == NUnit.Framework.Interfaces.TestStatus.Passed;            try            {                // Logs the result to Lambdatest                ((IJavaScriptExecutor)driver.Value).ExecuteScript("lambda-status=" + (passed ? "passed" : "failed"));            }            finally            {                // Terminates the remote webdriver session                driver.Value.Quit();            }        }    }}

Here is the Constants file for parallel tests.

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace ParallelLTSelenium{    public static class Constants    {        internal static string Username = "Your User Name";        internal static string AccessKey= "YOUR_LAMBDATEST_ACCESS_KEY";         internal static boolean tunnel = Environment.GetEnvironmentVariable("TUNNEL");        internal static string seleniumPort = Environment.GetEnvironmentVariable("SELENIUM_PORT");        internal static string build = "C# Sample App";        internal static string seleniumHost = Environment.GetEnvironmentVariable("SELENIUM_HOST");     }}

If you notice, with simple annotations and parameters, you can now run your test suite on multiple browsers every time, without changing the browser's parameters in code files every time.

Queuing#


To prevent over-exploitation of the platform, we have added a capacity constraint on the number of tests that can be queued at our platform. Your maximum queue capacity will be dependent upon the number of concurrent sessions your LambdaTest account is eligible for. The below formula will help you calculate the maximum capacity for your queue.


Maximum Queue Capacity

Maximum number of test cases that can be queued = n + 150

Here, n = number of concurrent sessions.

For instance, if you are opting for pricing where you can avail up to 10 concurrent sessions. Then the maximum number of test cases that can be queued will be equal to 10 + 150 i.e. 160 queued test cases. LambdaTest would automatically schedule and execute test cases for you.


Here you can get more information about LambdaTest Queuing Policy.

Note: Queuing Timeout There is also a limit on how long a test case can stay in the queue. If your test case stays in the queue for more than 15 minutes, the test case would be timed out and would not be executed.

Last updated on