Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

Selenium Web Driver Model View Controller Framework With C#

This example uses the console application explained in the article named "Selenium Web Driver with NUnit Console Application"

In this example you will learn how to use Model View Controller Framework (MVC Pattern)  in Selenium .Net test automation. The key feature of the sample is that you define all web elements in the site model class, so that you do not need to do change code in other classes that uses the web elements in your test.  This approach is very efficient when you have a dramatic UI change in your web application. You just need to update the element definition in the site element, so that your test application logic and work flow still work as before. 

Test result will be written as an html file, so that you can check the result on web browser. 

Ignore the TestRunner.cs file in this example's screenshot because it was part of the Selenium Web Driver with NUnit Console Application.

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 "TestRunnerMvc.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. Add a new item (class) and name it SiteModel.cs, which is used to define all the web elements. 


Step 3:

Write the following code in the SiteModel.cs class.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using OpenQA.Selenium;
  6.  
  7. namespace SeleniumMasterWebDriverDotNetTestSuiteAutomation
  8. {
  9.  
  10.     class SiteModel
  11.     {
  12.         protected static IWebDriver browser = null;
  13.  
  14.         //define Selenium Master Logo
  15.         public static IWebElement SeleniumMasterLogo()
  16.         {
  17.             return browser.FindElement(By.CssSelector("img[alt=\"Selenium Master\"]"));
  18.         }
  19.  
  20.         //define user name text box
  21.         public static IWebElement UserNameTextBox()
  22.         {
  23.             return browser.FindElement(By.Id("login_login_username"));
  24.         }
  25.         //define user password box
  26.         public static IWebElement UserPasswordTextBox()
  27.         {
  28.             return browser.FindElement(By.Id("login_login_password"));
  29.         }
  30.         //define submit button
  31.         public static IWebElement SubmitButton()
  32.         {
  33.             return browser.FindElement(By.Id("login_submit"));
  34.         }
  35.         //define online user message lable    
  36.         public static IWebElement OnLineUserMessage()
  37.         {
  38.             return browser.FindElement(By.CssSelector("ul.cr > li > a"));
  39.         }
  40.  
  41.         //define user settings link    
  42.         public static IWebElement UserSettingLink()
  43.         {
  44.             return browser.FindElement(By.LinkText("Settings"));
  45.         }
  46.  
  47.         //define user authorization radio button    
  48.         public static IWebElement AuthoriziationRadioButton()
  49.         {
  50.             return browser.FindElement(By.XPath("//input[@value='auth']"));
  51.         }
  52.  
  53.         //define save settings button
  54.  
  55.         public static IWebElement SaveSettings()
  56.         {
  57.             return browser.FindElement(By.Id("accountprefs_submit"));
  58.         }
  59.  
  60.         //define preference saved massage label
  61.  
  62.         public static IWebElement PreferenceSavedMessageLabel()
  63.         {
  64.             return browser.FindElement(By.CssSelector("div.ok"));
  65.         }
  66.  
  67.         //define Logout Link
  68.  
  69.         public static IWebElement LogoutLink()
  70.         {
  71.             return browser.FindElement(By.LinkText("Logout"));
  72.         }
  73.     }
  74. }

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:

write the following code in the TestRunnerMvc.cs class and inherit the SiteModel 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 TestRunnerMvc:SiteModel
  13.     {
  14.     private static String baseUrl;
  15.     TestResultUtility testResultUtility = new TestResultUtility();
  16.  
  17.         static void Main(string[] args)
  18.         {
  19.             //create a new test
  20.             TestRunnerMvc test = new TestRunnerMvc();
  21.             //execute Setup method
  22.             test.SetUp();
  23.             //run Launch Site and Login Method
  24.             test.launchSiteAndLogin();
  25.             //run Open User Setting Page Method
  26.             test.openUserSettingPage();
  27.             //run Change User Setting Method
  28.             test.ChangeUserSettings();
  29.             //run Logout Method
  30.             test.Logout();
  31.             //teardown the browser
  32.             test.TearDown();
  33.         }
  34.         //setup
  35.         public void SetUp()
  36.         {
  37.             //Initialize test result string
  38.             testResultUtility.InitializeTestResultString("Selenium Master Login Test Suite");
  39.             //test base url
  40.             baseUrl = "http://www.seleniummaster.com";
  41.             try
  42.             {
  43.                 //use firefox browser
  44.                 browser = new FirefoxDriver();
  45.                 //set browser time out time to 60 seconds
  46.                 browser.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(60));
  47.                 //add test result to test result string when passed
  48.                 testResultUtility.AddTestPassToTestResultString("Test Setup", "Pass");
  49.  
  50.             }
  51.             catch (Exception e)
  52.             {
  53.                //add message to the console
  54.                 Console.WriteLine(e.Message);
  55.                 Console.WriteLine("Cannot start Web Driver and Launch the browser");
  56.                 //add test result to test result string when failed
  57.                 testResultUtility.AddTestFailToTestResultString("Test Setup", "Fail");
  58.             }
  59.  
  60.         }
  61.     
  62.     //Launches the Selenium Master Test Application and Login
  63.     public void launchSiteAndLogin() {
  64.      browser.Navigate().GoToUrl(baseUrl + "/seleniummastertestapp/index.php");
  65.     //is site Logo displayed
  66.      IsElementPresentByElementName(SiteModel.SeleniumMasterLogo(), "Selenium Master Logo", 60);
  67.     //enter user name by using site model
  68.      SiteModel.UserNameTextBox().Clear();
  69.      SiteModel.UserNameTextBox().SendKeys("test");
  70.     //enter password by using site model
  71.      SiteModel.UserPasswordTextBox().Clear();
  72.      SiteModel.UserPasswordTextBox().SendKeys("XXXXXXX"); //password is omitted
  73.     //click on the submit button by using site model
  74.      SiteModel.SubmitButton().Click();
  75.          try
  76.          {
  77.  
  78. Assert.AreEqual(SiteModel.OnLineUserMessage().Text,"Test Selenium");
  79. testResultUtility.AddTestPassToTestResultString("Launch Site And Login Test", "Pass");
  80.          }
  81.         
  82.         catch
  83.         {
  84.             testResultUtility.AddTestFailToTestResultString("Launch Site And Login Test", "Fail");
  85.         }
  86.     }
  87.       
  88.     //Navigates to the User Settings page
  89.       public void openUserSettingPage() {
  90.         //click on Settings link by using site model
  91.         SiteModel.UserSettingLink().Click();
  92.         // is login user name text box displayed
  93.         IsElementPresentByElementName(SiteModel.UserNameTextBox(), "User name box", 60);
  94.         //enter user name by using site model
  95.         SiteModel.UserNameTextBox().Clear();
  96.         SiteModel.UserNameTextBox().SendKeys("test");
  97.         //enter password by using site model
  98.         SiteModel.UserPasswordTextBox().Clear();
  99.         SiteModel.UserPasswordTextBox().SendKeys("XXXXXXX"); //password is omitted
  100.         //click on the submit button by using site model
  101.         SiteModel.SubmitButton().Click();
  102.         //is user authorization radio button displayed
  103.         IsElementPresentByElementName(SiteModel.AuthoriziationRadioButton(), "user authrization button", 60);
  104.          try
  105.          {
  106. Assert.IsTrue(IsElementPresentByElementName(SiteModel.AuthoriziationRadioButton(), "user authrization button", 60));
  107. testResultUtility.AddTestPassToTestResultString("Open User Setting Page Test", "Pass");
  108.          }
  109.          catch
  110.          {
  111.              testResultUtility.AddTestFailToTestResultString("Open User Setting Page Test", "Fail");
  112.              
  113.          }
  114.         
  115.         
  116.     }
  117.       
  118.     //Change a User settings to add as a friends after authorization")
  119.       public void ChangeUserSettings() {
  120.         //click on the user authorization radio button click by using site model
  121.           SiteModel.AuthoriziationRadioButton().Click();
  122.           //click on the save settings button by using site model
  123.           SiteModel.SaveSettings().Click();
  124.           //is preference saved label displayed by using site model
  125.         IsElementPresentByElementName(SiteModel.PreferenceSavedMessageLabel(), "Save Settings", 60);
  126.         try
  127.         {
  128. Assert.AreEqual("Preferences saved",SiteModel.PreferenceSavedMessageLabel().Text);
  129. testResultUtility.AddTestPassToTestResultString("Change User Settings Test", "Pass");
  130.         }
  131.         
  132.           catch
  133.           {
  134.               testResultUtility.AddTestFailToTestResultString("Change User Settings Test", "Fail");
  135.           }
  136.  
  137.     }
  138.      
  139.     //Log out the system
  140.       public void Logout()
  141.       {
  142.          //is logout link displayed
  143.           IsElementPresentByElementName(SiteModel.LogoutLink(), "Logout link", 60);
  144.        //click on logout link
  145.           SiteModel.LogoutLink().Click();
  146.           try
  147.           {
  148.               Assert.IsTrue(IsElementPresentByElementName(SiteModel.SubmitButton(), "Submit Button", 60));
  149.               testResultUtility.AddTestPassToTestResultString("Logout Test", "Pass");
  150.           }
  151.           catch
  152.  
  153.           {
  154.               testResultUtility.AddTestFailToTestResultString("Logout Test", "Fail");
  155.           }
  156.           
  157.       }
  158.  
  159.     
  160.     //tear down
  161.     public void TearDown() {
  162.         testResultUtility.EndTestResultString();
  163.         testResultUtility.WriteToHtmlFile(testResultUtility.testResultHtmlString.ToString(), "SeleniumMasterLoginTestResult.html");
  164.        browser.Quit();
  165.     }
  166.     //define a method that keep checking if an element is displayed until time reaches 60 seconds
  167.       private bool IsElementPresentByElementName(IWebElement webElement, string elementName, int timeOutSeconds)
  168.       {
  169.           IWebElement currentElement;
  170.           DateTime currentTime = DateTime.Now;
  171.           TimeSpan duration;
  172.           for (int second = 0; ; second++)
  173.           {
  174.               DateTime newTime = DateTime.Now;
  175.               currentElement = webElement;
  176.               duration = newTime - currentTime;
  177.               if (currentElement.Displayed)
  178.               {
  179.                   Console.WriteLine("{0} is found", elementName);
  180.                   break;
  181.               }
  182.               if (duration.TotalSeconds >= timeOutSeconds)
  183.               {
  184.                   Console.WriteLine("{0} is Not found in {1} seconds", elementName, duration.TotalSeconds);
  185.                   break;
  186.               }
  187.           }
  188.           return currentElement.Displayed;
  189.       }
  190. }
  191.  
  192.     }

Step 6:

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.