Selenium with XUnit
Your guide to run Selenium Webdriver tests with XUnit 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 XUnit on BrowserStack is quick. This guide will help you to:
- Run your first test
- Integrate your tests with BrowserStack
- Mark tests as passed or failed
- Debug your app
Prerequisites
- 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.
-
XUnit
andXUnit.Runner
is installed from the NuGet Gallery. - Visual Studio is installed.
Run your first test
To run Selenium tests with XUnit on BrowserStack Automate, complete the following steps:
-
Clone the xunit-browserstack repository on GitHub with BrowserStack’s sample test, using the following command:
git clone https://github.com/browserstack/xunit-browserstack.git
-
Open the solution
XUnit-BrowserStack.sln
in Visual Studio. -
Set your BrowserStack Username and Access Key in the
config.json
file in thexunit-browserstack/XUnit-BrowserStack/
directory.{ "server": "hub.browserstack.com", "user": "YOUR_USERNAME", "key": "YOUR_ACCESS_KEY", "capabilities": { "bstack:options": { "buildName": "xunit-browserstack", "sessionName": "test", "debug": "true" } }, "environments": [ { "browserName": "chrome" }, { "browserName": "firefox" }, { "browserName": "safari" } ], "localOptions": { "forceLocal": true } }
- Run your first test on BrowserStack using the following command:
dotnet test --filter "profile=parallel"
- View your test results on the BrowserStack Automate dashboard.
Details of your first test
The following code is the sample XUnit test case that you ran. The test opens the bstackdemo.com
website, adds a product to the cart, and verifies whether the product is added to the cart.
using Xunit;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
namespace XUnit_BrowserStack
{
public abstract class ParallelBaseTest
{
private readonly BaseFixture baseFixture;
public ParallelBaseTest(BaseFixture baseFixture)
{
this.baseFixture = baseFixture;
}
public void BaseTest(string platform)
{
try
{
RemoteWebDriver driver = baseFixture.GetDriver(platform, "parallel");
WebDriverWait webDriverWait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(2000));
driver.Manage().Window.Maximize();
driver.Navigate().GoToUrl("https://bstackdemo.com/");
Assert.Equal("StackDemo", driver.Title);
string productOnPageText = webDriverWait.Until(driver => driver.FindElement(By.XPath("//*[@id=\"1\"]/p"))).Text;
webDriverWait.Until(driver => driver.FindElement(By.XPath("//*[@id=\"1\"]/div[4]"))).Click();
bool cartOpened = webDriverWait.Until(driver => driver.FindElement(By.XPath("//*[@class=\"float-cart__content\"]"))).Enabled;
Assert.True(cartOpened);
string productOnCartText = webDriverWait.Until(driver => driver.FindElement(By.XPath("//*[@id=\"__next\"]/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]"))).Text;
Assert.Equal(productOnCartText, productOnPageText);
baseFixture.SetStatus(cartOpened && productOnCartText.Equals(productOnPageText));
}
catch (Exception)
{
baseFixture.SetStatus(false);
throw;
}
}
}
public class ChromeTest : ParallelBaseTest, IClassFixture<BaseFixture>
{
public ChromeTest(BaseFixture baseFixture): base(baseFixture) { }
[Fact]
[Trait("profile", "parallel")]
public void Test()
{
BaseTest("chrome");
}
}
public class FirefoxTest : ParallelBaseTest, IClassFixture<BaseFixture>
{
public FirefoxTest(BaseFixture baseFixture) : base(baseFixture) { }
[Fact]
[Trait("profile", "parallel")]
public void Test()
{
BaseTest("firefox");
}
}
public class SafariTest : ParallelBaseTest, IClassFixture<BaseFixture>
{
public SafariTest(BaseFixture baseFixture) : base(baseFixture) { }
[Fact]
[Trait("profile", "parallel")]
public void Test()
{
BaseTest("safari");
}
}
}
Integrate your tests with BrowserStack
BrowserStack is integrated with your test using the BaseFixture.cs
file, which contains the methods to configure and create the connection with BrowserStack as follows:
using OpenQA.Selenium.Remote;
using Newtonsoft.Json.Linq;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium;
using BrowserStack;
namespace XUnit_BrowserStack
{
public class BaseFixture : IDisposable
{
private RemoteWebDriver? WebDriver;
private Local? browserStackLocal;
public RemoteWebDriver GetDriver(string platform, string profile)
{
// Get Configuration for correct profile
string currentDirectory = Directory.GetCurrentDirectory();
string path = Path.Combine(currentDirectory, "config.json");
JObject config = JObject.Parse(File.ReadAllText(path));
if (config is null)
throw new Exception("Configuration not found!");
// Get Platform specific capabilities
JObject capabilities = config.GetValue("environments").Where(x => x is JObject y && x["browserName"].ToString().Equals(platform)).ToList()[0] as JObject;
// Get Common Capabilities
JObject commonCapabilities = config.GetValue("capabilities") as JObject;
// Merge Capabilities
capabilities.Merge(commonCapabilities);
JObject bstackOptions = capabilities["bstack:options"] as JObject;
// Get username and accesskey
string? username = Environment.GetEnvironmentVariable("BROWSERSTACK_USERNAME");
if (username is null)
username = config.GetValue("user").ToString();
string? accessKey = Environment.GetEnvironmentVariable("BROWSERSTACK_ACCESS_KEY");
if (accessKey is null)
accessKey = config.GetValue("key").ToString();
bstackOptions["userName"] = username;
bstackOptions["accessKey"] = accessKey;
// Add session name
bstackOptions["sessionName"] = $"{profile}_test";
// Start Local if browserstack.local is set to true
if (profile.Equals("local") && accessKey is not null)
{
bstackOptions["local"] = true;
browserStackLocal = new Local();
List<KeyValuePair<string, string>> bsLocalArgs = new List<KeyValuePair<string, string>>() {
new KeyValuePair<string, string>("key", accessKey)
};
foreach (var localOption in config.GetValue("localOptions") as JObject)
{
if (localOption.Value is not null)
{
bsLocalArgs.Add(new KeyValuePair<string, string>(localOption.Key, localOption.Value.ToString()));
}
}
browserStackLocal.start(bsLocalArgs);
}
capabilities["bstack:options"] = bstackOptions;
// Create Desired Cappabilities for WebDriver
DriverOptions desiredCapabilities = getBrowserOption(capabilities.GetValue("browserName").ToString());
capabilities.Remove("browserName");
foreach (var x in capabilities)
{
if (x.Key.Equals("bstack:options"))
desiredCapabilities.AddAdditionalOption(x.Key, x.Value.ToObject<Dictionary<string, object>>());
else
desiredCapabilities.AddAdditionalOption(x.Key, x.Value);
}
// Create RemoteWebDriver instance
WebDriver = new RemoteWebDriver(new Uri($"https://{config["server"]}/wd/hub"), desiredCapabilities);
return WebDriver;
}
public void SetStatus(bool passed)
{
if(WebDriver is not null)
{
if (passed)
((IJavaScriptExecutor)WebDriver).ExecuteScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"passed\", \"reason\": \"Test Passed!\"}}");
else
((IJavaScriptExecutor)WebDriver).ExecuteScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"failed\", \"reason\": \"Test Failed!\"}}");
}
}
static DriverOptions getBrowserOption(String browser)
{
switch (browser)
{
case "chrome":
return new OpenQA.Selenium.Chrome.ChromeOptions();
case "firefox":
return new OpenQA.Selenium.Firefox.FirefoxOptions();
case "safari":
return new OpenQA.Selenium.Safari.SafariOptions();
case "edge":
return new OpenQA.Selenium.Edge.EdgeOptions();
default:
return new OpenQA.Selenium.Chrome.ChromeOptions();
}
}
public void Dispose()
{
if (WebDriver is not null)
{
WebDriver.Quit();
WebDriver.Dispose();
}
if(browserStackLocal is not null)
{
browserStackLocal.stop();
}
}
}
}
Mark tests as passed or failed
BrowserStack provides a comprehensive REST API to access and update information about your tests. The following sample code allows you to mark your tests as passed or failed based on the assertions in your XUnit test cases.
namespace RestApi {
class ChangeSessionStatus {
static void Main(string[] args) {
string reqString = "{\"status\":\"passed\", \"reason\":\"\"}";
byte[] requestData = Encoding.UTF8.GetBytes(reqString);
Uri myUri = new Uri(string.Format("https://www.browserstack.com/automate/sessions/<session-id>.json"));
WebRequest myWebRequest = HttpWebRequest.Create(myUri);
HttpWebRequest myHttpWebRequest = (HttpWebRequest)myWebRequest;
myWebRequest.ContentType = "application/json";
myWebRequest.Method = "PUT";
myWebRequest.ContentLength = requestData.Length;
using (Stream st = myWebRequest.GetRequestStream())st.Write(requestData, 0, requestData.Length);
NetworkCredential myNetworkCredential = new NetworkCredential("YOUR_USERNAME", "YOUR_ACCESS_KEY");
CredentialCache myCredentialCache = new CredentialCache();
myCredentialCache.Add(myUri, "Basic", myNetworkCredential);
myHttpWebRequest.PreAuthenticate = true;
myHttpWebRequest.Credentials = myCredentialCache;
myWebRequest.GetResponse().Close();
}
}
}
Check out the full reference to our REST API for more information.
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 JUnit tests. 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 debug
capability to true
.
"capabilities": {
"bstack:options": {
"debug": "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
.
"capabilities": {
"bstack:options": {
"video": "false"
}
},
In addition to these logs BrowserStack also provides Raw Logs, Network Logs, Console Logs, Selenium Logs, Appium Logs and Interactive session. You can find the complete details to enable 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:
- Run multiple tests in parallel to speed up the build execution
- Migrate existing tests to BrowserStack
- Name your tests and organize your builds
- Mark Tests as Passed or Failed
- 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!