Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

Selenium Web Driver with NUnit Console Application

When using Selenium Web Driver with NUnit C#, if tests need to run sequencially,  writing a test automation Console Application is a good approach.  

In this example you will learn how to use Selenium WebDriver with NUnit. The key feature of the sample is that you use Selenium .Net WebDriver that will launch a browser and run each test sequencially in the console application. Test result will be written as an html file, so that you can check the result on web browser.  

Model your test cases 

Before you start automation, you need to know what are the tests and what you are going to validate. Let's break the test suite into 4 test cases. 

Test 1 (launchSiteAndLogin)
1. Go to http://www.seleniummaster.com/seleniummastertestapp/index.php
2. Enter "test" in the Username field
3. Enter "XXXX" in the Password filed
4. Click on the Login button
5. Verify that the text "Selenium Test" is present.

 

Test 2 (openUserSettingPage)
1. Click on the Settings link on the top of the page
2. Enter "test" in the Username field
3. Enter "XXXX" in the Password filed
4. Click on the Login button
5. Verify that Account Prefernces page displayed.

Test 3 (ChangeUserSettings)
1. Click on the radio button near friends need my authorization to add me
2. Click on the save button
3. Verify that the text "preference saved" displayed.

Test4 (Logout)
1. Click on the Logout button
2. Verify that Login button displayed.

Automation Implementation

Step 1: Run Visual Studio and create a New Project. Select Console Application under Visual C# in the Installed Templates section on the New Project Window. 

 

Step 2: In the Name, enter "SeleniumMasterWebDriverDotNetTestSuiteAutomation". Add Selenium .Net library dlls as References. Also add nunit.framework in the references. By default, the solution has a class name called "Program.cs". Rename it as "TestRunner.cs", which is used to launch the test application. Add a new item (class) and name it TestResultUtility, which is used for generating test result html string and test result output file.  

Step 3: Write the following code in the TestRunner.cs class. 

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using OpenQA.Selenium.Firefox;
  6. using OpenQA.Selenium.Support.UI;
  7. using OpenQA.Selenium;
  8. using System.Threading;
  9. using NUnit.Framework;
  10. namespace SeleniumMasterWebDriverDotNetTestSuiteAutomation
  11. {
  12.     class TestRunner
  13.     {
  14.     private static IWebDriver browser;
  15.     private static String baseUrl;
  16.     TestResultUtility testResultUtility = new TestResultUtility();
  17.  
  18.         static void Main(string[] args)
  19.         {
  20.             //create a new test
  21.             TestRunner test = new TestRunner();
  22.             //execute Setup method
  23.             test.SetUp();
  24.             //run Launch Site and Login Method
  25.             test.launchSiteAndLogin();
  26.             //run Open User Setting Page Method
  27.             test.openUserSettingPage();
  28.             //run Change User Setting Method
  29.             test.ChangeUserSettings();
  30.             //run Logout Method
  31.             test.Logout();
  32.             //teardown the browser
  33.             test.TearDown();
  34.         }
  35.         //setup
  36.         public void SetUp()
  37.         {
  38.             //Initialize test result string
  39.             testResultUtility.InitializeTestResultString("Selenium Master Login Test Suite");
  40.             //test base url
  41.             baseUrl = "http://www.seleniummaster.com";
  42.  
  43.             try
  44.             {
  45.                 //use firefox browser
  46.                 browser = new FirefoxDriver();
  47.                 //set browser time out time to 60 seconds
  48.                 browser.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(60));
  49.                 //add test result to test result string when passed
  50.                 testResultUtility.AddTestPassToTestResultString("Test Setup", "Pass");
  51.  
  52.             }
  53.             catch (Exception e)
  54.             {
  55.                //add message to the console
  56.                 Console.WriteLine(e.Message);
  57.                 Console.WriteLine("Cannot start Web Driver and Launch the browser");
  58.                 //add test result to test result string when failed
  59.                 testResultUtility.AddTestFailToTestResultString("Test Setup", "Fail");
  60.             }
  61.  
  62.         }
  63.     
  64.     //Launches the Selenium Master Test Application and Login
  65.     public void launchSiteAndLogin() {
  66.      browser.Navigate().GoToUrl(baseUrl + "/seleniummastertestapp/index.php");
  67.             for (int second = 0;; second++) {
  68.                 if (second >= 60) Assert.Fail("timeout");
  69.                 try { if (isElementPresent(By.CssSelector("img[alt=\"Selenium Master\"]")))
  70.                     break; } catch (Exception e) {
  71.                         Console.WriteLine(e.Message);
  72.                     }
  73.                 Thread.Sleep(1000);
  74.             }
  75.         
  76.          browser.FindElement(By.Id("login_login_username")).Clear();
  77.          browser.FindElement(By.Id("login_login_username")).SendKeys("test");
  78.          browser.FindElement(By.Id("login_login_password")).Clear();
  79.          browser.FindElement(By.Id("login_login_password")).SendKeys("XXXX"); //password is omitted
  80.          browser.FindElement(By.Id("login_submit")).Click();
  81.          try
  82.          {
  83. Assert.AreEqual(browser.FindElement(By.CssSelector("ul.cr > li > a")).Text,"Test Selenium");
  84. testResultUtility.AddTestPassToTestResultString("Launch Site And Login Test", "Pass");
  85.          }
  86.         
  87.         catch
  88.         {
  89.             testResultUtility.AddTestFailToTestResultString("Launch Site And Login Test", "Fail");
  90.         }
  91.     }
  92.       
  93.     //Navigates to the User Settings page
  94.       public void openUserSettingPage() {
  95.         browser.FindElement(By.LinkText("Settings")).Click();
  96.         
  97.          for (int second = 0;; second++) {
  98.                 if (second >= 60) Assert.Fail("timeout");
  99.                 try { if (isElementPresent(By.Id("login_login_username")))
  100.                     break; } catch (Exception e) {
  101.                         Console.WriteLine(e.Message);
  102.                     }
  103.                 Thread.Sleep(1000);
  104.             }
  105.         
  106.          browser.FindElement(By.Id("login_login_username")).Clear();
  107.          browser.FindElement(By.Id("login_login_username")).SendKeys("test");
  108.          browser.FindElement(By.Id("login_login_password")).Clear();
  109.          browser.FindElement(By.Id("login_login_password")).SendKeys("XXXX");//password is omitted
  110.          browser.FindElement(By.Id("login_submit")).Click();
  111.         
  112.          for (int second = 0;; second++) {
  113.                 if (second >= 60) Assert.Fail("timeout");
  114.                 try { if (isElementPresent(By.XPath("//input[@value='auth']")))
  115.                     break; } catch (Exception e) {
  116.                         Console.WriteLine(e.Message);
  117.                     }
  118.                 Thread.Sleep(1000);
  119.             }
  120.          try
  121.          {
  122. Assert.IsTrue(isElementPresent(By.XPath("//input[@value='auth']")));
  123. testResultUtility.AddTestPassToTestResultString("Open User Setting Page Test", "Pass");
  124.          }
  125.          catch
  126.          {
  127.              testResultUtility.AddTestFailToTestResultString("Open User Setting Page Test", "Fail");
  128.              
  129.          }
  130.         
  131.         
  132.     }
  133.       
  134.     //Change a User settings to add as a friends after authorization")
  135.       public void ChangeUserSettings() {
  136.         browser.FindElement(By.XPath("//input[@value='auth']")).Click();
  137.         browser.FindElement(By.Id("accountprefs_submit")).Click();
  138.         for (int second = 0; ; second++)
  139.         {
  140.             if (second >= 60) Assert.Fail("timeout");
  141.             try
  142.             {
  143.                 if (isElementPresent(By.CssSelector("div.ok")))
  144.                     break;
  145.             }
  146.             catch (Exception e)
  147.             {
  148.                 Console.WriteLine(e.Message);
  149.             }
  150.             Thread.Sleep(1000);
  151.         }
  152.         try
  153.         {
  154. Assert.AreEqual("Preferences saved",browser.FindElement(By.CssSelector("div.ok")).Text);
  155. testResultUtility.AddTestPassToTestResultString("Change User Settings Test", "Pass");
  156.         }
  157.         
  158.           catch
  159.           {
  160.               testResultUtility.AddTestFailToTestResultString("Change User Settings Test", "Fail");
  161.           }
  162.  
  163.     }
  164.      
  165.     //Log out the system
  166.       public void Logout()
  167.       {
  168.           for (int second = 0; ; second++)
  169.           {
  170.               if (second >= 60) Assert.Fail("timeout");
  171.               try
  172.               {
  173.                   if (isElementPresent(By.LinkText("Logout")))
  174.                       break;
  175.               }
  176.               catch (Exception e)
  177.               {
  178.                   Console.WriteLine(e.Message);
  179.               }
  180.               Thread.Sleep(1000);
  181.           }
  182.           browser.FindElement(By.LinkText("Logout")).Click();
  183.           try
  184.           {
  185.               Assert.IsTrue(isElementPresent(By.Id("login_login_username")));
  186.               testResultUtility.AddTestPassToTestResultString("Logout Test", "Pass");
  187.           }
  188.           catch
  189.  
  190.           {
  191.               testResultUtility.AddTestFailToTestResultString("Logout Test", "Fail");
  192.           }
  193.           
  194.       }
  195.  
  196.     
  197.     //tear down
  198.     public void TearDown() {
  199.         testResultUtility.EndTestResultString();
  200.         testResultUtility.WriteToHtmlFile(testResultUtility.testResultHtmlString.ToString(), "SeleniumMasterLoginTestResult.html");
  201.        browser.Quit();
  202.     }
  203.     
  204.       private bool isElementPresent(By by) {
  205.             try {
  206.               browser.FindElement(by);
  207.               return true;
  208.             } catch (NoSuchElementException e) {
  209.                 Console.WriteLine(e.Message);
  210.               return false;
  211.             }
  212.           }
  213. }
  214.  
  215.     }

Step 4: Write the following code in the TestResultUtility.cs class. 

 

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.IO;
  5. using System.Text;
  6.  
  7. namespace SeleniumMasterWebDriverDotNetTestSuiteAutomation
  8. {
  9.     class TestResultUtility
  10.     {
  11.         public StringBuilder testResultHtmlString;
  12.  
  13.         public void InitializeTestResultString(String TestSuiteName)
  14.         {
  15.             testResultHtmlString = new StringBuilder();
  16.             testResultHtmlString.Append("<html><header><title>").Append(TestSuiteName).Append("</title></header><body><table border=\"1\">");
  17.             testResultHtmlString.Append("<tr style=\"background-color:#99CCFF\"><td><b> Test Case </b></td><td><b> Test Result </b></td></tr>");
  18.  
  19.         }
  20.  
  21.         public void AddTestPassToTestResultString(String TestMethod, String TestResult)
  22.         {
  23.             //add green color to the background if pass
  24.             testResultHtmlString.Append("<tr style=\"background-color:#33CC33\"><td>").Append(TestMethod).Append("</td><td>").Append(TestResult).Append("</td></tr>");
  25.  
  26.         }
  27.         public void AddTestFailToTestResultString(String TestMethod, String TestResult)
  28.         {
  29.             //add yellow color to the background if fail
  30.             testResultHtmlString.Append("<tr style=\"background-color:#FFFF00\"><td>").Append(TestMethod).Append("</td><td>").Append(TestResult).Append("</td></tr>");
  31.  
  32.         }
  33.         public void EndTestResultString()
  34.         {
  35.             testResultHtmlString.Append("</table></body></html>");
  36.         }
  37.         public void WriteToHtmlFile(String content, String filename)
  38.         {
  39.             //Create a file stream
  40.             FileStream file = new FileStream(filename, FileMode.OpenOrCreate);
  41.             StreamWriter sw = new StreamWriter(file);
  42.             //writing to the file
  43.             sw.WriteLine(content);
  44.             sw.Close();
  45.         }
  46.     }
  47. }

Step 5: run the test and check the result file in this folder. 

C:/SeleniumMasterDotNetTestAutomation/SeleniumMasterWebDriverDotNetTestSuiteAutomation/bin/Debug/SeleniumMasterLoginTestResult.html

Test Case Test Result
Test Setup Pass
Launch Site And Login Test Pass
Open User Setting Page Test Pass
Change User Settings Test Pass
Logout Test Pass

The html result file above indicated that all the test steps passed. You can also run the test without the Visual Studio environment. 

just run the executable file "SeleniumMasterWebDriverDotNetTestSuiteAutomation.exe" file. 

Note: you can customize the test result file by adding test time stamp, test username, test computer name and other diagnostic information.