Ever had to test something on a piece of software over and over again? Maybe on a monthly, weekly or daily basis? Well, in this article, I will show you how to use a piece of software known as Selenium WebDriver that will get you started on reproducible testing that will literally save you hours, even days, and sometimes weeks.
My name is Tyler Wood. I have been working at FNC, Inc. for eight years now. I started as an intern and found small automated solutions that worked for filling out forms. Eventually I built my own C# desktop applications that would submit post XMLs to interfaces to help our manual testers perform at an optimal pace. Eventually I started using Microsoft’s coded UI, which gave great scalability in terms of record and playback browser automation. However, the ultimate tool I have found for browser automation is Selenium WebDriver using C#.
At FNC we have many specialties, and one of them includes quality assurance software automation. Over the past few years, FNC has been looking into the most in-depth browser automation, performance test automation, and load testing automation. When Microsoft folded Lab Management into Visual Studio 2012 Premium (previously it was only included with Ultimate), our goal was to get nightly and on-demand automation set up.
My first question was: Where do we even get started? Well, first let me explain what Microsoft Lab Center allows you to do.
• It allows you to run full test plans, test suites, and test cases using web drivers or unit tests that expect a result, and spits out failures if the desired result is not as expected.
• It allows scheduled runs to occur once per day at any desired time.
• It gives test analysis and managerial graphs that display the number of tests run, failed or passed.
• Logging: It gives IntelliTraces for developers with Microsoft Visual Studio Ultimate Licenses, event logs and system logs.
In the following article, I will demonstrate how to set up a unit test solution that will use Selenium. In Part Two, I will cover how to create a build definition that will automatically import test cases into Test Case Manager.
Part 1) Getting Started: Selenium Project Setup
1) Navigate to VS 2012/2013 and Create a New Unit Test Solution in C# (name it whatever, this is your solution) Example. SoftwareUnwoundSelenium
2) Delete the first UnitTest1.cs
3) Add to your project a new item, navigate to Visual C# Items -> Test -> “Unit Test” (this will give you the test initializer method, test clean up method)
4) Click on Tools -> NuGet Package Manager -> Manage Nuget Packages for Solution
5) Click “online” on the left
6) Search by keyword: Selenium
7) Download/Install: Selenium WebDriver, Selenium WebDriver Support Classes, WebDriver-backed Selenium, Selenium Remote Control.
8) * OPTIONAL * Search by “Chrome driver” and install it. (Selenium uses Firefox as its default)
Getting Started: Test Configuration
1) With your new UnitTest1.cs, go ahead and rename it to GoogleTest.cs.
2) Add the following references to the top of your class:
A) (if Chrome)
using OpenQA.Selenium.Chrome;
(else if Firefox)
using OpenQA.Selenium.Firefox; B) using OpenQA.Selenium.Support; using OpenQA.Selenium.Support.UI; using OpenQA.Selenium.Support.Events; using OpenQA.Selenium.Interactions;
3) Uncomment TestInitialize() and TestCleanup()
// Use TestInitialize to run code before running each test // [TestInitialize()] // public void MyTestInitialize() { } // // Use TestCleanup to run code after each test has run // [TestCleanup()] // public void MyTestCleanup() { }
4) Delete the constructor Public GoogleTest()
Add a private variable used for the web driver.
For example, private IWebDriver ChromeDriver;
5) Rename the method of MyTestInitialize() to SyncDriver()
6) Rename the method of MyTestCleanUp() to DriverCleanup()
7) Add the following code to the SyncDriver() method
// New up the driver to boot up a new browser for each test ChromeDriver = new ChromeDriver(); // This will maximize your window to 100%
8) Add the following code to the DriverCleanUp() method
//breaks driver down if not in use after each test run if (ChromeDriver != null) ChromeDriver.Quit();
9) The following attributes can be removed to keep things tidy since we will not need them for this demonstration:
#region Additional test attributes // // You can use the following additional attributes as you write your tests: // // Use ClassInitialize to run code before running the first test in the class // [ClassInitialize()] // public static void MyClassInitialize(TestContext testContext) { } // // Use ClassCleanup to run code after all tests in a class have run // [ClassCleanup()] // public static void MyClassCleanup() { } //
10) Your class should now look something like this:
using System; using System.Text; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Support; using OpenQA.Selenium.Support.UI; using OpenQA.Selenium.Support.Events; using OpenQA.Selenium.Interactions; namespace SoftwareUnwoundSelenium { [TestClass] public class GoogleTest { private IWebDriver ChromeDriver; private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } [TestInitialize()] public void SyncDriver() { // New up the driver to boot up a new browser for each test ChromeDriver = new ChromeDriver(); // This will maximize your window to 100% ChromeDriver.Manage().Window.Maximize(); } [TestCleanup()] public void DriverCleanup() { // breaks driver down if not in use //if (ChromeDriver != null) // ChromeDriver.Quit(); } [TestMethod] public void NavigateToGoogle() { ChromeDriver.Navigate().GoToUrl("https://google.com"); }
Getting Started: Writing Your First Test
1) Rename TestMethod1() to NavigateToGoogle()
2) Type the following:
ChromeDriver.Navigate().GoToUrl(https://www.google.com);
3) Build by pressing Ctrl+Shift+B or by clicking the Build Menu –> Build
Your test should be ready to be run at any point, and your test class should look like this:
4) Right-click on the test and click “Run Selected Test.” Go to Google, and then shut the browser down.
To see if the browser navigated correctly, comment the Chrome driver cleanup:
[TestCleanup()] public void DriverCleanup() { // breaks driver down if not in use //if (ChromeDriver != null) // ChromeDriver .Quit(); }
5) Rebuild and run, and the browser will stay open. Congrats! You have just written your first test and learned how to navigate to URLs.
Testing: Selecting Elements
1) Uncomment the last step in “Writing your First Test,” and create a new test method named ClickOnGoogleSearchFieldandSearch().
2) Copy and paste the code you added in NavigateToGoogle()
3) Open Chrome and navigate to https://www.google.com.
4) Press F12 on your keyboard to bring up “Developer Tools”
5) Click on the magnifying glass icon and click on the search field
An HTML tag should pop up with an ID, a class, and a name.
The Selenium user should have basic knowledge of how HTML is rendered in the Document Object Model (DOM). Every time a web page loads, the DOM is rendered with the full-blown HTML. The Selenium user has to use these HTML elements in order to perform actions, whether they are typing, clicking, or selecting a dropdown value.
6) In your project use the Search by ID feature by typing the following:
IWebElement SearchTextField = ChromeDriver.FindElement(By.Id("gbqfq"));
7) You can also use By.CssSelector(“input[id=’gbqfq’]”), By.Name(“q”), By.Class(“gbqfif”)
8) Rebuild and run your test. When you log in, behind the scenes the driver should be able to select the search bar by the element ID “gbqfq.”
Testing: Performing Actions with Elements
1) Continuing the code you used in Step 8 of “Selecting Elements,” we will now enter some text in the search field via Google.
2) Beneath “SearchTextField”, enter the following:
SearchTextField.SendKeys("Selenium HQ");
This will type the keys into the Search field of Google.
Method should look like this:
[TestMethod] public void ClickOnGoogleSearchFieldandSearch() { ChromeDriver.Navigate().GoToUrl("https://google.com"); // Typing Keys into an Element using By Id - Example Below is a Text Field IWebElement SearchTextField = ChromeDriver.FindElement(By.Id("gbqfq")); SearchTextField.SendKeys("Selenium HQ"); // Clicking on an Element - Example Below is a Button IWebElement SearchButton = ChromeDriver.FindElement(By.Id("gbqfb")); SearchButton.Click(); }
3) Rebuild and run the test
• Test should navigate to Google
• Test should find the element for the search field
• Test should enter text into the search field
Conclusion: Other Selectors, Actions and Winding Down:
There are many other ways of selecting elements on the screen. It is preferable to have IDs added to each HTML element, but that is not always possible. As the quality assurance engineer, you have to be inventive in finding ways to reach elements within the DOM. Often, you may have to use By.CssSelector, but other times you have to use By.Xpath. I insist using CSS Selectors because the CSS is less likely to change than Xpath. If developers add more HTML elements such as divs/spans, the test is harder to maintain by the quality assurance engineer. Xpath is the last option one should use to select an element.
Additionally, there will be times where you will need to navigate into windows, iframes, and other HTML elements. In these scenarios, you will need to instruct the driver to do so. The command is “(name of driver).SwitchTo.” Example:
// Step into IFRAME var framemenu = wait.Until (x => x.FindElement(By.Id("frmenu"))); var framedrivermenu = ChromeDriver.Switchto().Frame(framemenu);
Moving forward, you will need to select attributes in dropdown lists; select specific text onscreen; or click on an element (button). If you need to grab attributes, you will discover a GetAttribute() feature that comes in handy. If you need to grab the text, most will simply use the .Text property in order to do so (labels or text fields). Last, to click on a button, all you need to do is select the element and then call the .Click method:
public static void LoginSubmitButton(IWebDriver ChromeDriver) { IWebElement Submit = ChromeDriver.FindElement(By.Id(LoginData.LoginControls.LoginSubmitButton));Submit.Click(); }
In Part Two we will be diving into refactoring the tests into Page models and Data models in order to supply my dynamic variables for test data. This will also make it easier for reusable tests/code for negative testing. Additionally, I will be giving feedback on good valid assertions. Afterward, I will be explaining the differences between explicit and implicit waits and how to implement them. Last I will be explaining the usage of data-driven testing using a database to load data into tests.
In Part Three we will be using Lab Center and setting up tests into Microsoft Test Manager. This will also touch on Build Definitions for importing and scheduling nightly or running on-demand builds.
Great post! Thank you very much for this, many of the “initial setup” tutorials or examples on the internet are way out of date. Can’t wait for the follow up posts! 🙂
Simon,
I’m glad it helped. I will hopefully have something in the next two weeks in regards to Part 2 Intermediate Usage of Selenium Webdriver. The Lab Center edition (Part 3) will be more for Lab Managers of Microsoft Test Manager, so this may or may not apply to you.
Take Care
Great Post .I was struggling to understand Selenium and your steps helped to me to get started .Thanks so much for posting ..Are you done with Part2 and Part3 ?? If so let me know where i can find it …Thanks GIta
Gita, I will definitely be putting some stuff together here soon. It’s been discussed to create a “sample” test site with advanced navigation using Xpath / CssSelector. Also I will discuss usage of SQL and how to preload data with test initializers. Stay tuned near May and you shall hear something from me. Glad it helped and thanks for the comment.