CrossBrowserTesting Support

Support

  • Product
    • Live Testing
    • Automated Testing
    • Record & Replay
    • Visual Testing
  • API Docs
  • Blog
  • Live Q&A
  • Start Testing
CrossBrowserTesting Support » Selenium Testing » C Sharp » Selenium and C#

Selenium and C#

Getting Started With Selenium + C#

Selenium is a great tool to automate our functional tests on websites and web applications in our favorite language. With CrossBrowserTesting, you can use Selenium and C# to run automated browser tests on thousands of real mobile and desktop browsers in the cloud. To learn more about the Selenium API, we recommend you read Selenium’s documentation which can be found here.

You’ll need a Username and Authkey to run your tests on CrossBrowserTesting. To get yours, sign up for a free trial or purchase a plan.

Installing Selenium

To get started let’s make sure we have the necessary assembly references for our test script. If you copy the following script into Visual Studio, it should try to do this for you:


// Getting started: http://docs.seleniumhq.org/docs/03_webdriver.jsp
// API details: https://github.com/SeleniumHQ/selenium#selenium
// Quick start video tutorial using Visual Studio: https://www.youtube.com/watch?v=CxDkRJ1iHwE
// Step-by-step video turoial using Visual Studio: https://www.youtube.com/watch?v=uRJL0zu7U6k

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using NUnit.Framework;
using OpenQA.Selenium; using OpenQA.Selenium.Remote; using OpenQA.Selenium.Chrome;
using System.Collections.Generic; namespace BasicTest { class BasicTest { // put your username and authkey here: public static string username = "YOUR_USERNAME"; public static string authkey = "YOUR_AUTHKEY"; static void Main(string[] args) { var cbtapi = new CBTApi();

IDictionary<string, string> cbtOptions = new Dictionary<string, string>();

cbtOptions.Add("record_video", "true");
cbtOptions.Add("screenResolution", "1920x1080"); // Start by setting the capabilities ChromeOptions caps = new ChromeOptions(); caps.PlatformName = "Windows 10"; caps.BrowserVersion = "84"; caps.AddAdditionalCapability("username", username, true); caps.AddAdditionalCapability("password", authkey, true);
caps.AddAdditionalCapability("cbt:options", cbtOptions, true); // Start the remote webdriver RemoteWebDriver driver = new RemoteWebDriver(new Uri("http://hub.crossbrowsertesting.com:80/wd/hub"), caps.ToCapabilities(), TimeSpan.FromSeconds(180)); // wrap the rest of the test in a try-catch for error logging via the API try { // Maximize the window - DESKTOPS ONLY // driver.Manage().Window.Maximize(); // Navigate to the URL driver.Navigate().GoToUrl("http://crossbrowsertesting.github.io/selenium_example_page.html"); // Check the title Console.WriteLine(driver.Title); Assert.AreEqual(driver.Title, "Selenium Test Example Page"); // Uncomment this line to see what happens when an assertion fails! // Assert.AreEqual(driver.Title, "Selenium Test Example Cage"); cbtapi.setScore(driver.SessionId.ToString(), "pass"); driver.Quit(); } catch (AssertionException ex) { var snapshotHash = cbtapi.takeSnapshot(driver.SessionId.ToString()); cbtapi.setDescription(driver.SessionId.ToString(), snapshotHash, ex.ToString()); cbtapi.setScore(driver.SessionId.ToString(), "fail"); Console.WriteLine("caught the exception : " + ex); driver.Quit(); throw new AssertionException(ex.ToString()); } } } public class CBTApi { public string BaseURL = "https://crossbrowsertesting.com/api/v3/selenium"; public string username = BasicTest.username; public string authkey = BasicTest.authkey; public string takeSnapshot(string sessionId) { // returns the screenshot hash to be used in the setDescription method. // create the POST request object pointed at the snapshot endpoint HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BaseURL + "/" + sessionId + "/snapshots"); Console.WriteLine(BaseURL + "/" + sessionId); request.Method = "POST"; request.Credentials = new NetworkCredential(username, authkey); request.ContentType = "application/x-www-form-urlencoded"; request.UserAgent = "HttpWebRequest"; // Execute the request var response = (HttpWebResponse)request.GetResponse(); // store the response var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); // parse out the snapshot Hash value var myregex = new Regex("(?<=\"hash\": \")((\\w|\\d)*)"); var snapshotHash = myregex.Match(responseString).Value; Console.WriteLine(snapshotHash); return snapshotHash; } public void setDescription(string sessionId, string snapshotHash, string description) { // encode the data to be written ASCIIEncoding encoding = new ASCIIEncoding(); var putData = encoding.GetBytes("description=" + description); // create the request HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BaseURL + "/" + sessionId + "/snapshots/" + snapshotHash); request.Method = "PUT"; request.Credentials = new NetworkCredential(username, authkey); request.ContentType = "application/x-www-form-urlencoded"; request.UserAgent = "HttpWebRequest"; // write data to stream Stream newStream = request.GetRequestStream(); newStream.Write(putData, 0, putData.Length); newStream.Close(); WebResponse response = request.GetResponse(); } public void setScore(string sessionId, string score) { string url = BaseURL + "/" + sessionId; // encode the data to be written ASCIIEncoding encoding = new ASCIIEncoding(); string data = "action=set_score&score=" + score; byte[] putdata = encoding.GetBytes(data); // Create the request HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "PUT"; request.Credentials = new NetworkCredential(username, authkey); request.ContentLength = putdata.Length; request.ContentType = "application/x-www-form-urlencoded"; request.UserAgent = "HttpWebRequest"; // Write data to stream Stream newStream = request.GetRequestStream(); newStream.Write(putdata, 0, putdata.Length); newStream.Close(); WebResponse response = request.GetResponse(); } } }

Now, add references using Project -> Add Reference. Selenium should be one of them. We’ll also be using NUnit to make assertions during our test.

Once you have all the necessary assembly references in place, we’ll run our first test. If you have the app open as well, navigate to the Selenium side of our app. As you can see we also create a CBTApi object that allows us to set the score, take a snapshot, and set the description.

Test Capabilities

CrossBrowserTesting allows you to add certain capabilities to your test, like video recordings, naming structure and more.

Naming Tests

Naming your tests can help organize your automated test cases for easier debugging. You can also mark Build number to denote releases.

  cbtOptions.Add("name", "Selenium Example");

 

  cbtOptions.Add("build", "1.0");

Choosing Browsers

To choose your environment, you can select from Browsers, Operating System, Resolutions, and Devices. You can use our easy Selenium Wizard to select your configuration or hit our browser list endpoint.

Recording Videos

For superior debugging capabilities, CrossBrowserTesting offers the ability to record a video of your Selenium test session. You can find a copy of your test results here.

  cbtOptions.Add("record_video", "true");

 

Recording Network

To record the network packets during your test for performance debugging, set the following to “true”.

  cbtOptions.Add("record_network", "true");

 

Running A Local Test

With our Local Tunnel, you can run a test on a local URL or behind your company’s firewall. There are two different ways to connect the CrossBrowserTesting local tunnel: our NodeJS client and our Chrome Extension.

You can read more about setting up, starting, and using your tunnel connection here.

When a tunnel is open, any automated test can access websites locally, behind a firewall, or across a proxy. There is no need to set a capability during your test.

Troubleshooting

Related

Selenium Starting Guides

  • Python
  • Java
  • JavaScript
  • PHP
  • Ruby
  • C#
  • Selenium 101

C#

  • Specflow
  • NUnit

More Help

  • Parallel Testing
  • Jenkins Integration
  • TeamCity Integration
  • Automation Capabilities
  • Local Testing

See Our GitHub Examples


 



Think you need a human?

Our customer success team will be glad to help you with your question.

Contact Support

Still need a free trial?

Try CrossBrowserTesting free for 7 days and see how we make testing easier.

Start Today

Want the latest tips?

Enter your email and we’ll send you tutorials and browser testing strategies right to your inbox.


Product

  • Live Testing
  • Automated Testing
  • Visual Testing
  • Local Testing
  • Integrations

Resources

  • Browsers & Devices
  • Blog
  • Webinars
  • Security
  • ROI Calculator

Support

  • Help Center
  • CBT Community
  • API Docs
  • Automation Docs
  • Schedule A Demo
  • Enterprise Request

Company

    • About Us
    • Contact Us
    • Careers
    • Terms of Use
    • 1-888-927-6973

© 2019 CrossBrowserTesting.com, LLC. All rights reserved.