Skip to end of metadata
Go to start of metadata

Sauce Labs is a cloud platform for executing automated and manual mobile and web tests. Sauce Labs supports running automated tests with Selenium WebDriver (for web applications) and Appium (for native and mobile web applications). In this topic you'll see an example of how to run a test with Selenium Webdriver for C#.NET on Sauce Labs, and how to set up some tools that will help you get the most out of your Sauce Labs testing experience. 

Example Only

The code in this topic is presented as an example only, since your tests and testing environments may require specialized scripting. This information should be taken only as an illustration of how you could set up your tests with Sauce Labs, and is not directly supported by Sauce.

Prerequisites

Before getting started, you should review the Best Practices for Running Tests.

You need to have these components installed to set up testing on Sauce with C#.NET:

Installing Selenium WebDriver

You can also download the Selenium driver for C# from the official Selenium HQ website, where you can find additional documentation about working with Selenium.

  1. Open a new project in Visual Studio.
  2. Select a C# class library template.
  3. Give the project a name and click OK.
  4. In the Visual Studio Tools menu, go to Library Package Manager > Manage Nuget Package for Solution
    This will open the Manage NuGet Packages screen.
  5. Click Online, and then click Next.
  6. In the Search Packages field, enter Selenium and then click Search.
  7. In the search results, select Selenium Webdriver and then click Install.

Installing Selenium DLLs

After you’ve set up your project in Visual Studio, you need to make sure that it references the necessary Selenium DLLs for .NET.

  1. Download the Selenium DLLs for .NET from http://selenium-release.storage.googleapis.com/index.html?path=2.47/
  2. In the Solutions Explorer, select the project and right-click References.
  3. Click Add Reference.
  4. Click Browse and navigate to the net40 folder of the directory where you saved the Selenium .NET DLLs.
  5. Add the WebDriver.Support.dll reference to your project.

Installing NUnit

NUnit is a unit-test framework for all .Net languages, written entirely in C# and designed to take advantage of many .NET language features, for example custom attributes and other reflection-related capabilities. For more information and documentation about the framework, as well as how to use it in your testing, you can visit the official NUnit website.

  1. Download the current stable release of NUnit from http://www.nunit.org/index.php?p=download.
  2. In the Solutions Explorer, select the project and right-click References.
  3. Click Add Reference.
  4. Click Browse and navigate to the bin of the directory where you saved NUnit.
  5. Add the nunit.framework.dll and pnunit.framework.dll reference to your project.

Code Example

SaucePNUnit_Test.cs

This example test opens Google, verifies that “Google” is the title of the page, and then searches for Sauce Labs. It connects to Sauce Labs, run commands to remote control the target browser, and reports the results. It also includes the code for running tests in parallel and reporting the results to your Sauce Labs dashboard. 

You can use the Platform Configurator to specify the desired capabilities for any browser/platform combination you want for your test. 

You can clone this script directly from our GitHub repo.

PNUnit_Test.cs Sample Script
using NUnit.Framework;
using System;
using Selenium;
using System.Web;
using System.Text;
using System.Net;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;

namespace Saucey_Selenium {
    [TestFixture("chrome", "45", "Windows 7", "", "")]
    public class SauceNUnit_Test
    {
        private IWebDriver driver;
        private String browser;
        private String version;
        private String os;
        private String deviceName;
        private String deviceOrientation;

        public SauceNUnit_Test(String browser, String version, String os, String deviceName, String deviceOrientation)
        {
            this.browser = browser;
            this.version = version;
            this.os = os;
            this.deviceName = deviceName;
            this.deviceOrientation = deviceOrientation;
        }

        [SetUp]
        public void Init()
        {
            DesiredCapabilities caps = new DesiredCapabilities();
            caps.SetCapability(CapabilityType.BrowserName, browser);
            caps.SetCapability(CapabilityType.Version, version);
            caps.SetCapability(CapabilityType.Platform, os);
            caps.SetCapability("deviceName", deviceName);
            caps.SetCapability("deviceOrientation", deviceOrientation);
            caps.SetCapability("username", "SAUCE_USERNAME");
            caps.SetCapability("accessKey", "SAUCE_ACCESS_KEY");
            caps.SetCapability("name", TestContext.CurrentContext.Test.Name);

            driver = new RemoteWebDriver(new Uri("http://ondemand.saucelabs.com:80/wd/hub"), caps, TimeSpan.FromSeconds(600))

        }

        [Test]
        public void googleTest()
        {
            driver.Navigate().GoToUrl("http://www.google.com");
            StringAssert.Contains("Google", driver.Title);
            IWebElement query = driver.FindElement(By.Name("q"));
            query.SendKeys("Sauce Labs");
            query.Submit();
        }

        [TearDown]
        public void CleanUp()
        {
            var passed = TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Passed;
            ((IJavaScriptExecutor)Driver).ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed"));
            Driver?.Quit();
        }
    }
}

Selenium 3 Example

The use of Desired Capabilities is deprecated for C# in Selenium 3. This example illustrates how to set the platform/operating system/browser for C# using Selenium 3.

using NUnit.Framework;
using NUnit.Framework.Interfaces;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Remote;
using System;

namespace SeleniumNunit
{
    [TestFixture]
    public class GettingStartedTest
    {
        IWebDriver Driver;
        /// <summary>
        /// This is a simple Sauce Labs test to help you get started.
        /// This does NOT follow the recommeded best practices for test automation.
        /// </summary>
        ///
        [Test]
        public void SampleSauceTest()
        {
            //TODO please supply your Sauce Labs user name in an environment variable
            var sauceUserName = Environment.GetEnvironmentVariable("SAUCE_USERNAME", EnvironmentVariableTarget.User);
            //TODO please supply your own Sauce Labs access Key in an environment variable
            var sauceAccessKey = Environment.GetEnvironmentVariable("SAUCE_ACCESS_KEY", EnvironmentVariableTarget.User);

            ChromeOptions options = new ChromeOptions();
            options.AddAdditionalCapability(CapabilityType.Version, "latest", true);
            options.AddAdditionalCapability(CapabilityType.Platform, "Windows 10", true);
            options.AddAdditionalCapability("username", sauceUserName, true);
            options.AddAdditionalCapability("accessKey", sauceAccessKey, true);
            options.AddAdditionalCapability("name", TestContext.CurrentContext.Test.Name, true);

            Driver =  new RemoteWebDriver(new Uri("http://ondemand.saucelabs.com:80/wd/hub"), options.ToCapabilities(),
                TimeSpan.FromSeconds(600));
            Driver.Navigate().GoToUrl("https://www.google.com");
            Assert.Pass();
        }

        [TearDown]
        public void CleanUpAfterEveryTestMethod()
        {
            var passed = TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Passed;
            ((IJavaScriptExecutor)Driver).ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed"));
            if(Driver != null)
                Driver.Quit();
        }
    }
}

Installing the NUnit Test Adapter and Running the Test

  1. Select Tools > Extension Manager.
  2. In the left panel of the Extension Manager, select Online Extensions.
  3. Locate the NUnit Test Adapter in the center panel and select it.
  4. Click Download and follow the instructions.
  5. Go to Test > Windows > Test Explorer to view the NUnit Test Adapter.
    You should now see the Test Explorer tab on the left side of your project
  6. Go to Build > Build Solution to build the project, or use the CTRL-SHIFT-B shortcut. 
    When you initially open a solution, no tests will be displayed. After compiling the assemblies in the solution, Visual Studio will interact with the NUnit Test Adapter to discover tests and a list of them will be shown in the Test Explorer.
  7. Click Run All to launch your test to the Sauce Dashboard

Running Local Tests

Developing websites/apps within your local network is secure and efficient. The drawback to this method is that local assets are not publicly-accessible on the Internet, so the browsers/devices in the Sauce Labs cloud can't load and test your app. The solution is to use Sauce ConnectSauce Connect is a proxy server that creates a secure tunnel connection between the Sauce Labs virtual machine that runs your test and your local  network. You can also use Sauce Connect to test applications and websites that are located within your corporate firewall. Sauce Connect is not required to run tests on Sauce Labs, only in situations where the application or website you want to test is not publicly accessible. 

Running Tests in Parallel

Now that you’re running tests on Sauce, you may wonder how you can run your tests faster. One way to increase speed is by running tests in parallel across multiple virtual machines.

You can run your tests in parallel at two levels, and you can run your tests in parallel across multiple browsers. For example, if you have 10 tests and want to run on five browsers, this would be parallelism of five. You can also run tests across browsers and each test in parallel. Using our previous example this would be more like 50 parallel tests. Doing this requires that your tests are written in a way that they do not collide with one another, as described in our Best Practice topics avoiding external test dependencies and avoiding dependencies between tests.

Match Thread Count to Concurrency Limit

You should match your thread count to your concurrency limit, which is shown in the My Account section of your user profile information on the Sauce Labs dashboard.  

For more information, check out the example scripts in our GitHub repo

Reporting Test Results

This example test opens Google, verifies that “Google” is the title of the page, and then searches for Sauce Labs. It connects to Sauce Labs, run commands to remote control the target browser, and reports the results. It also includes the code for running tests in parallel and reporting the results to your Sauce Labs dashboard. 

You can use the Platform Configurator to specify the desired capabilities for any browser/platform combination you want for your test. 

You can clone this script directly from our GitHub repo.

PNUnit_Test.cs Sample Script
using NUnit.Framework;
using System;
using Selenium;
using System.Web;
using System.Text;
using System.Net;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;

namespace Saucey_Selenium {
    [TestFixture("chrome", "45", "Windows 7", "", "")]
    public class SauceNUnit_Test
    {
        private IWebDriver driver;
        private String browser;
        private String version;
        private String os;
        private String deviceName;
        private String deviceOrientation;

        public SauceNUnit_Test(String browser, String version, String os, String deviceName, String deviceOrientation)
        {
            this.browser = browser;
            this.version = version;
            this.os = os;
            this.deviceName = deviceName;
            this.deviceOrientation = deviceOrientation;
        }

        [SetUp]
        public void Init()
        {
            DesiredCapabilities caps = new DesiredCapabilities();
            caps.SetCapability(CapabilityType.BrowserName, browser);
            caps.SetCapability(CapabilityType.Version, version);
            caps.SetCapability(CapabilityType.Platform, os);
            caps.SetCapability("deviceName", deviceName);
            caps.SetCapability("deviceOrientation", deviceOrientation);
            caps.SetCapability("username", "SAUCE_USERNAME");
            caps.SetCapability("accessKey", "SAUCE_ACCESS_KEY");
            caps.SetCapability("name", TestContext.CurrentContext.Test.Name);

            driver = new RemoteWebDriver(new Uri("http://ondemand.saucelabs.com:80/wd/hub"), caps, TimeSpan.FromSeconds(600))

        }

        [Test]
        public void googleTest()
        {
            driver.Navigate().GoToUrl("http://www.google.com");
            StringAssert.Contains("Google", driver.Title);
            IWebElement query = driver.FindElement(By.Name("q"));
            query.SendKeys("Sauce Labs");
            query.Submit();
        }

        [TearDown]
        public void CleanUp()
        {
            var passed = TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Passed;
            ((IJavaScriptExecutor)Driver).ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed"));
            Driver?.Quit();
        }
    }
}

Selenium 3 Example

The use of Desired Capabilities is deprecated for C# in Selenium 3. This example illustrates how to set the platform/operating system/browser for C# using Selenium 3.

using NUnit.Framework;
using NUnit.Framework.Interfaces;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Remote;
using System;

namespace SeleniumNunit
{
    [TestFixture]
    public class GettingStartedTest
    {
        IWebDriver Driver;
        /// <summary>
        /// This is a simple Sauce Labs test to help you get started.
        /// This does NOT follow the recommeded best practices for test automation.
        /// </summary>
        ///
        [Test]
        public void SampleSauceTest()
        {
            //TODO please supply your Sauce Labs user name in an environment variable
            var sauceUserName = Environment.GetEnvironmentVariable("SAUCE_USERNAME", EnvironmentVariableTarget.User);
            //TODO please supply your own Sauce Labs access Key in an environment variable
            var sauceAccessKey = Environment.GetEnvironmentVariable("SAUCE_ACCESS_KEY", EnvironmentVariableTarget.User);

            ChromeOptions options = new ChromeOptions();
            options.AddAdditionalCapability(CapabilityType.Version, "latest", true);
            options.AddAdditionalCapability(CapabilityType.Platform, "Windows 10", true);
            options.AddAdditionalCapability("username", sauceUserName, true);
            options.AddAdditionalCapability("accessKey", sauceAccessKey, true);
            options.AddAdditionalCapability("name", TestContext.CurrentContext.Test.Name, true);

            Driver =  new RemoteWebDriver(new Uri("http://ondemand.saucelabs.com:80/wd/hub"), options.ToCapabilities(),
                TimeSpan.FromSeconds(600));
            Driver.Navigate().GoToUrl("https://www.google.com");
            Assert.Pass();
        }

        [TearDown]
        public void CleanUpAfterEveryTestMethod()
        {
            var passed = TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Passed;
            ((IJavaScriptExecutor)Driver).ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed"));
            if(Driver != null)
                Driver.Quit();
        }
    }
}

1 Comment

  1. Anonymous

    Why github code reference (https://github.com/saucelabs-sample-scripts/C-Sharp-Selenium) and sample code shown here  are different and using different Test framworks.wiki page using Nunit but github not using NUnit.  Why this page is referring code that is not compilable? Is this really live product documentation?