Selenium with C#
Your guide to run Selenium Webdriver tests with C# on BrowserStack.
The sample test script in this section is compatible with W3C-based client bindings. Check out our JSON wire protocol-based scripts in the selenium-3 branch of the repository.
Introduction
BrowserStack gives you instant access to our Selenium Grid of 3000+ real devices and desktop browsers. Running your Selenium tests with C# on BrowserStack is simple. This guide will help you:
Prerequisites
- You need to have BrowserStack Username and Access key, which you can find in your account settings. If you have not created an account yet, you can sign up for a Free Trial or purchase a plan.
- Before you can start running your Selenium tests with C# you have to set up visual studio project with Selenium bindings as shown below (you can skip this section if you already have a working C# setup to run Selenium tests):
- Open visual studio and create a new empty project as shown below:
- Once the project is loaded go to File -> New File and create an empty C# file as shown below:
- Go to Project -> Manage NuGet Packages as shown below:
- Search for Webdriver and Select Selenium.WebDriver and Add Package as shown below:
Now, your setup is ready to run the first Selenium test.
Run your first test
To get started, let’s run a simple Selenium Webdriver test. The C# script below opens the bstackdemo.com
website, adds a product to the cart, verifies whether the product has been added to the cart, and then marks the test as passed or failed based on whether the product is available in the cart.
Step 1 - Create a sample test code file
Copy the following code into the empty class file that you created in the Pre-requisite step and save it as Parallel.cs
:
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Safari;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Edge;
using OpenQA.Selenium.IE;
using System.Threading;
using System;
using System.Collections.Generic;
namespace MultiThreading
{
class BrowserStackOptions : DriverOptions
{
public BrowserStackOptions(String browser_name, String browser_version)
{
this.BrowserName = browser_name;
this.BrowserVersion = browser_version;
}
[Obsolete]
public override void AddAdditionalCapability(string capabilityName, object capabilityValue)
{
this.AddAdditionalOption(capabilityName, capabilityValue);
}
public override ICapabilities ToCapabilities()
{
IWritableCapabilities capabilities = this.GenerateDesiredCapabilities(true);
return capabilities.AsReadOnly();
}
}
class MultiThreading
{
static void Main(string[] args)
{
Dictionary<string, object> cap1 = new Dictionary<string, object>();
cap1.Add("deviceName", "Samsung Galaxy S22 Plus");
cap1.Add("browserName", "Samsung");
cap1.Add("osVersion", "12.0");
Dictionary<string, object> cap2 = new Dictionary<string, object>();
cap2.Add("deviceName", "iPhone 12 pro");
cap2.Add("osVersion", "14");
cap2.Add("browserName", "ios");
Dictionary<string, object> cap3 = new Dictionary<string, object>();
cap3.Add("os", "OS X");
cap3.Add("osVersion", "Big Sur");
cap3.Add("browserName", "Firefox");
cap3.Add("browserVersion", "latest");
//Creating Threads and defining the browser and OS combinations where the test will run
Thread t1 = new Thread(obj => sampleTestCase(cap1));
Thread t2 = new Thread(obj => sampleTestCase(cap2));
Thread t3 = new Thread(obj => sampleTestCase(cap3));
//Executing the methods
t1.Start();
t2.Start();
t3.Start();
t1.Join();
t2.Join();
t3.Join();
}
static void sampleTestCase(Dictionary<string, object> cap)
{
// Update your credentials
String BROWSERSTACK_USERNAME = "YOUR_USERNAME";
String BROWSERSTACK_ACCESS_KEY = "YOUR_ACCESS_KEY";
String BUILD_NAME = "browserstack-build-1";
cap.Add("userName", BROWSERSTACK_USERNAME);
cap.Add("accessKey", BROWSERSTACK_ACCESS_KEY);
cap.Add("buildName", BUILD_NAME);
String browserVersion = cap.ContainsKey("browserVersion") == true ? (string)cap["browserVersion"] : "";
var browserstackOptions = new BrowserStackOptions((string)cap["browserName"], browserVersion);
browserstackOptions.AddAdditionalOption("bstack:options", cap);
executeTestWithCaps(browserstackOptions);
}
//executeTestWithCaps function takes capabilities from 'sampleTestCase' function and executes the test
static void executeTestWithCaps(DriverOptions capability)
{
IWebDriver driver = new RemoteWebDriver(new Uri("https://hub.browserstack.com/wd/hub/"), capability);
try
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
driver.Navigate().GoToUrl("https://bstackdemo.com/");
// getting name of the product
String product_on_page = wait.Until(driver => driver.FindElement(By.XPath("//*[@id=\"1\"]/p"))).Text;
// clicking the 'Add to Cart' button
IWebElement cart_btn = driver.FindElement(By.XPath("//*[@id='1']/div[4]"));
wait.Until(driver => cart_btn.Displayed);
cart_btn.Click();
// waiting for the Cart pane to appear
wait.Until(driver => driver.FindElement(By.ClassName("float-cart__content")).Displayed);
// getting name of the product in the cart
String product_in_cart = driver.FindElement(By.XPath("//*[@id='__next']/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]")).Text;
if (product_on_page == product_in_cart)
{
((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"passed\", \"reason\": \" Product has been successfully added to the cart!\"}}");
}
}
catch
{
((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"failed\", \"reason\": \" Some elements failed to load.\"}}");
}
driver.Quit();
}
}
}
driver.quit()
statement is required, otherwise the test continues to execute, leading to a timeout.
Step 2 - Run the sample test code
Run the script using the following command:
dotnet run Program.cs parallel
Step 3 - Verify the results
Once the test has run successfully, it is time to verify the results. The Selenium Webdriver test should have opened bstackdemo.com
, added a product to the cart, verified whether the product has been added to the cart, and marked the test as passed or failed based on whether the product is available in the cart.
Mark tests as passed or failed
BrowserStack does not know whether your test’s assertions have passed or failed because only the test script knows whether the assertions have passed. Therefore, based on the assertions on your script, you have to explicitly inform BrowserStack whether your tests have passed or not and this document will help you in doing that exactly.
It is possible to mark tests as either a pass or a fail and also give a reason for the same, using the following snippet:
// For marking test as passed
((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"passed\", \"reason\": \" Yaay! my sample test passed\"}}");
// For marking test as failed
((IJavaScriptExecutor)driver).ExecuteScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"failed\", \"reason\": \" Oops! my test failed \"}}");
You can refer to the sample script, given in Step 1, to learn implementation of this code snippet.
status
and reason
.
-
status
accepts eitherpassed
orfailed
as the value -
reason
accepts a value in string datatype
Marking test as pass/fail is also possible using our REST API at any point in the test or also after the test has concluded. You can read more about marking test using REST API and use it, if it fits your use case.
Debug your app
BrowserStack provides a range of debugging tools to help you quickly identify and fix bugs you discover through your automated tests.
Text logs
Text Logs are a comprehensive record of your test. They are used to identify all the steps executed in the test and troubleshoot errors for the failed step. Text Logs are accessible from the Automate dashboard or via our REST API.
Visual logs
Visual Logs automatically capture the screenshots generated at every Selenium command run through your C# script. Visual logs help with debugging the exact step and the page where failure occurred. They also help identify any layout or design related issues with your web pages on different browsers.
Visual Logs are disabled by default. In order to enable Visual Logs you will need to set browserstack.debug
capability to true
:
capability.AddAdditionalCapability("browserstack.debug", "true", true);
Sample Visual Logs from Automate Dashboard:
Video recording
Every test run on the BrowserStack Selenium grid is recorded exactly as it is executed on our remote machine. This feature is particularly helpful whenever a browser test fails. You can access videos from Automate Dashboard for each session. You can also download the videos from the Dashboard or retrieve a link to download the video using our REST API.
browserstack.video
capability to false
.
In addition to these logs BrowserStack also provides Raw logs, Network logs, Console logs, Selenium logs, Appium logs and Interactive session. Read more about enabling all the debugging options.
Next steps
Once you have successfully run your first test on BrowserStack, you might want to do one of the following:
- Migrate existing tests to BrowserStack
- Run multiple tests in parallel to speed up the build execution
- Test on private websites that are hosted on your internal networks
- Select browsers and devices where you want to test
- Set up your CI/CD: Jenkins, Bamboo, TeamCity, Azure, CircleCI, BitBucket, TravisCI, GitHub Actions
We're sorry to hear that. Please share your feedback so we can do better
Contact our Support team for immediate help while we work on improving our docs.
We're continuously improving our docs. We'd love to know what you liked
We're sorry to hear that. Please share your feedback so we can do better
Contact our Support team for immediate help while we work on improving our docs.
We're continuously improving our docs. We'd love to know what you liked
Thank you for your valuable feedback!