Browse Category: Webdriver

Selenium with C#

Basic WebDriver and C# script for beginners

WebDriver Test using C# and Visual Studio 2013 Express.


One of my video is getting multiple hit for how to write WebDriver or selenium tests using C#. There are many tutorials available on internet for Java but not many for WebDriver and C#. I will teach you how to write test scenario in C#. I have visual Studio 2013 express edition.

Step1: Create WebDriver Project

Create new Project, and choose ‘Unit Test Project’, and give some name says; ‘AddItemToShoppingCart’ and hit OK button.

Create new Unit Test Project

You will see following folder structure and if you open UnitTest1.cs, you will see code

Step1.1C# Code In Visual Studio

 

Rename file, UnitTest1.cs to some logical name and class name inside the code as well.

Step2: Add WebDriver into reference.

Go to Manage NuGet Packages and search for WebDriver.

C# Manage NuGet Package

Select latest version of WebDriver and Selenium WebDriver Support Classes item and click Install button to install.

Webdriver and WebDriver Support files

After installation, you can see WebDriver and WebDriver.support in Reference under Solution Explorer.

Step2.2

Search ‘Selenium chrome’ and install Chrome Driver that will add chromedriver.exe into your project.

Step2.3

Step 3 (optional if you want to use NUnit instead of inbuilt UnitTestFramework in Visual Studio)

Now to you need to install NUnit before writing NUnit. Search NUnit in NuGet Package and Install. To use lean more about NUnit and attributes, please refer Learn Nunit tutorial. In this Tutorial I will Use predefined Unit Test Framework and its attributes.

Step 4: Write WebDriver Code

Now real implementation starts here. This article will talk about Visual Studio Unit Test tool which is even new for me too. This UnitTest namespace has three main test attributes which I am going to use.

  1. The [TestClass] attribute is required in Microsoft Unit Test Framework for any class that contains Test method and you want to run in Test Explore. Class with Attribute [TestClass] must have Test method.
  2. The [TestMethod] attribute is to assign a method inside [TestClass] to run actual test code.
  3. The [TestInitialize] attribute need to assign to the method which runs prior to running any [TestMethod] attribute method.
  4. The [TestCleanup] attribute method is to run after [TestMethod] method.

[TestInitialize] attribute method will have the code to do all setup like, defining any variable required for code, initializing WebDriver, opening url etc.

[TestMethod] attribute method will have actual test code which will run after [TestInitialize] and all kind of action and verification will take place in this method.

[TestCleanup] attribute method will be have code to clean up all kind of setting or action like removing any special setup or logout from application and close application. This method can have the code to preparing the reports etc.

Test Explorer will show only methods with attribute [TestMethod].

Step4.1

Step5: Start Writing Code

This section will have real coding.

We have two scenarios to implement

  1. We want to open an ecommerce website and pick nexus phone and add into cart and verify if cart has that item before proceeding to checkout.
  2. Check if you can open find makeup brush.

 

If you write both scenarios in steps:

 

Scenario 1 Scenario 2
1.       Open Brower2.       Open application under test says: donethedeal.com3.       Click on nexus phone link that will take you to the description page.4.       Click on Add to Cart and wait for confirmation if phone added to cart.5.       Open Cart link from top menu and verify if Phone is present there.

6.       Close the browser.

1.       Open Browser2.       Open application under test says: donethedeal.com3.       Open brush page4.       Verify that if item has description of brush

 

 

5.       Close the browser.

If you check above you will see that we have common steps in both scenarios which we can move to common area for each scenario and that will go to [TestInitialize] and last step in [TestCleanup.]

Before writing actual code, you need to add the reference for selenium into the code as follows;

using OpenQA.Selenium;

using OpenQA.Selenium.Chrome; //to use googlechrome browser.

using OpenQA.Selenium.Support;

[TestInitialize]

In this step you need to initialize the browser, let’s say Firefox using Firefox Driver. You initialize interface IWebDriver in the [TestClass] that controls the browser and have url for application under test so these will be available across the class.

Now you need to initialize the Firefox/chrome browser and once it is open, you need to open the url to cover step 1 and step2.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support;
using ExcelReader;

namespace AddItemToShoppingCart
{
    [TestClass]
    public class VerifyItems
    {
        IWebDriver driver;
        string url = "http://learnseleniumtesting.com/demo/";
        [TestInitialize]    
        public void TestSetup()
        {
            driver = new ChromeDriver();
            driver.Navigate().GoToUrl(url);
        }
}

 

[TestCleanup]

This attribute method will run at the end so we want to close the browser here. You just need to call driver.Quit() to close the browser.

[TestCleanup]

public void Cleanup()

{

driver.Quit();

}

[TestMethod]

Method with this attribute will contains the actual code. Create a public method with some logical name and assign the attribute. For now keep the method blank build the solution.

Overall code should look like this;

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support;
 
namespace AddItemToShoppingCart
{
    [TestClass]
    public class VerifyItems
    {
        IWebDriver driver;
        string url = "http://learnseleniumtesting.com/demo/";
        [TestInitialize]
        public void TestSetup()
        {
            driver = new ChromeDriver();
            driver.Navigate().GoToUrl(url);
        }
        [TestCleanup]
        public void Cleanup()
        {
            driver.Quit();
        }
        [TestMethod]
        public void AddPhoneToCartAndVerifyInCart()
        {
            //This is the placeholder to write actual code.
        }
 
    }
 }


 Test The Code:

Open Test Explorer window and you will see as below. To test the code click on the ‘Run All’ option in the Test Explorer windows. You will see new chrome browser instance launched and loaded www.donethedeal.com website and close the browser. You can add some wait in Test method in case if you want to make sure if it goes to TestMethod or not.

You can run that test in debug mode and you can put break point into your code and step through that. To run in debug mode you need to run test via Test Tool bar. Select the test in Test Explorer and Go to Test->Debug->Selected Test.

Test Code Implementation

Now we will work on implementation of test Steps.

// Click on nexus phone link that will take you to the description page

To perform above step. You just need to click on the application that will eventually take you the details page of the Nexus phone. Since we have only two products on the Test application then it is easy to write.

driver.FindElement(By.PartialLinkText("Nexus")).Click();
var summary = driver.FindElement(By.CssSelector("#product-18 > div.row > div.col-md-7 > div > div.product_meta > span > span")).Text;

You just need to click on the application that will eventually take you the details page of the Nexus phone. Since we have only two products on the Test application then it is quick to execute. If you run that you will notice that product description page appeared and then closes the browser. We need to have some verification framework. For that We can use Assert.

And code will look like this:

driver.FindElement(By.PartialLinkText("Nexus")).Click();
            var sku = driver.FindElement(By.CssSelector("#product-18 > div.row > div.col-md-7 > div > div.product_meta > span > span")).Text;
            Assert.AreEqual("10001", sku);

Assert call with is to verify items.

Later you can add following code to verify cart.

[TestMethod]
        public void AddPhoneToCartAndVerifyInCart()
        {
            
            driver.FindElement(By.PartialLinkText("Nexus")).Click();
            var sku = driver.FindElement(By.CssSelector("#product-18 > div.row > div.col-md-7 > div > div.product_meta > span > span")).Text;
            Assert.AreEqual("10001", sku);
            driver.FindElement(By.CssSelector("#product-18 > div.row > div.col-md-7 > div > form > button")).Click();
            //Verify if item added to cart. 
            driver.FindElement(By.XPath("//*[@id='content']/div/div/div[2][contains(text(), 'was successfully added to your cart')]"));

            //Clikc Go to cart\
            driver.FindElement(By.CssSelector("#content > div > div > div.woocommerce-message > a")).Click();
            var dd = driver.FindElement(By.XPath("//*[@id='content']/div/div/div/form/table/tbody/tr[1]/td[1]")).Text;
            
            //Verify If one phone given the cart.
            Assert.AreEqual("×", driver.FindElement(By.XPath("//*[@id='content']/div/div/div/form/table/tbody/tr[1]/td[1]")).Text);
            Assert.AreEqual("1", driver.FindElement(By.XPath("//*[@id='content']/div/div/div/form/table/tbody/tr[1]/td[5]")).Text);
            Assert.AreEqual("Proceed to Checkout", driver.FindElement(By.CssSelector("#content > div > div > div > form > table > tbody > tr:nth-child(2) > td > a")).Text);
        }

Execute the test either in run mode and or debug mode and see the result. It will be pass. If its failing then try to give some pause wherever required

 

Note: Avoid using any hard wait in script though.

 

In similar way you need to write another Test case where you just click on brush and verify the description and close the browser. And overall code will look like:

 

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support;
using ExcelReader;
namespace AddItemToShoppingCart
{
    [TestClass]
    public class VerifyItems
    {
        IWebDriver driver;
        string url = "http://learnseleniumtesting.com/demo/";
        [TestInitialize]
        public void TestSetup()
        {
            
            driver = new ChromeDriver();
            driver.Navigate().GoToUrl(url);
        }
        [TestCleanup]
        public void Cleanup()
        {
            driver.Quit();
        }

        [TestMethod]
        public void AddPhoneToCartAndVerifyInCart()
        {
            
            driver.FindElement(By.PartialLinkText("Nexus")).Click();
            var sku = driver.FindElement(By.CssSelector("#product-18 > div.row > div.col-md-7 > div > div.product_meta > span > span")).Text;
            Assert.AreEqual("10001", sku);
            driver.FindElement(By.CssSelector("#product-18 > div.row > div.col-md-7 > div > form > button")).Click();
            //Verify if item added to cart. 
            driver.FindElement(By.XPath("//*[@id='content']/div/div/div[2][contains(text(), 'was successfully added to your cart')]"));

            //Clikc Go to cart\
            driver.FindElement(By.CssSelector("#content > div > div > div.woocommerce-message > a")).Click();
            var dd = driver.FindElement(By.XPath("//*[@id='content']/div/div/div/form/table/tbody/tr[1]/td[1]")).Text;
            
            //Verify If one phone given the cart.
            Assert.AreEqual("×", driver.FindElement(By.XPath("//*[@id='content']/div/div/div/form/table/tbody/tr[1]/td[1]")).Text);
            Assert.AreEqual("1", driver.FindElement(By.XPath("//*[@id='content']/div/div/div/form/table/tbody/tr[1]/td[5]")).Text);
            Assert.AreEqual("Proceed to Checkout", driver.FindElement(By.CssSelector("#content > div > div > div > form > table > tbody > tr:nth-child(2) > td > a")).Text);
        }
        [TestMethod]
        public void VerifyBrushDescription()
        {
            driver.FindElement(By.PartialLinkText("Brush")).Click();
            var description = driver.FindElement(By.CssSelector("#product-28 > div.row > div.col-md-7 > div > h1")).Text;
            Assert.AreEqual("Makeup Brush", description);
        }
    }
}

Final Result

I am using C# and Visual Studio 2013 Express Edition. Code given in video is different than the code given in this blog.

Please change quality of video to HD so you can see the code clearly.

Hopefully this video is helpful for the beginners who want to learn or use WebDriver with .NET framework
Please don’t forget to like/comment on video if you have any suggestion or you like this.

Sample Website: http://learnseleniumtesting.com/demo/

How to use WebDriver to handle dropdown or select tag



We can use regular webdriver command to handle most of webelements like check box, text box etc. but to handle dropdown or select element as given below

<select id="sel123">

<option value="my">My</option>

<option value="name">Name</option>

<option value="is">Is</option>

<option value="admin">Admin</option>

</select>

you can use following code.

IWebElement sTag = driver.FindElement(By.Id("sel123"));
OpenQA.Selenium.Support.UI.SelectElement selectTag = new OpenQA.Selenium.Support.UI.SelectElement(sTag);
selectTag.SelectByValue("admin");
//Or
selectTag.SelectByText("Admin");
//Or
selectTag.SelectByIndex(3);

In case if you want to verify how many options are available in select tag then use following:

 var availableOptions = selectTag.Options;
 foreach (IWebElement item in availableOptions)
 {
    Console.WriteLine(item.Text);
 }

Selenium GRID and Nunit

Everyone asking about how to setup Selenium GRID. We were using Visual Studio to execute script which was kind of time consuming. It used to take minium 1.5 hours after every build. After that I implemented GRID and divided  tests into groups based on category and ran in parallel and achieved 66% improvement. Not bad ;).

If you have any question, I will try to answer. If you are using webdriver and want to use grid then you need to use remote webdriver instead. Every thing will be the same.

Remember: If you try to use two instances of Firefox execution in parallel in same machine , you won’t be able to but chrome will work.

If you find this useful please don’t forget to like the page below :)