.SHARP{C#DERS}

.net development, server management, and related topics

Selenium UI Tests Using NUnit and Visual Studio 2013

Setting up UI tests can be easy but can also be a little frustrating.  After setting up my tests in NUnit, each test case would run fine on their own but when trying to run all the tests at once as if they were in a suite, the tests would act as if they were timing out.    My problem was a new instance of the browser was not started at the beginning of each test case.  To solve the problem, a new function was added that would return a new web browser and another one that would close the browser and quit the tests see the browser.cs code example.

Below is a sample of the project and the solution to the problem.  When running the tests run them and debug them making sure that a new instance of the browser is created. 

My project was broken down into several different class files for each area of the site that was to be tested.  The files can be accessed on GiHub by going to:  https://github.com/ericdc1/AliaSQL-Demo.   This is a team repository that we are sharing as we learn new things in our development environment.  The structure was as follows:

  • PageObjects – contains folders broken down by section of the web site,  each folder contains a page actions and a page elements file.
  • Tests – contains all test cases names consist of the area of the site being tested.
  • Utilities – contains the base, browser and page actions classes that are used throughout the project.

Sample basic page actions class, which is referenced on most pages.

using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.PageObjects;
using Sample.Core.Models;
using SampleAutomatedTesting.Utilties;
using SampleUITests.PageObjects.Basic;
using SampleUITests.Utilities;
 
namespace SampleUITests.PageObjects.Login
{
    public class BasicPageActions
    {
 
        public static void GoTo()
        {
            Browser.StartWebDriver();
            var URL = "http://sampleproject.com";
            Browser.Goto(URL);
        }
 
    ...
 
        public static void StopTests()
        {
            Browser.StopTests();
        }
    }
}

Sample basic page elements class, common elements referenced in most tests:

using System.Net.Mime;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
 
namespace SampleUITests.PageObjects.Basic
{
   public  class BasicPageElements
    {
        [FindsBy(How = How.ClassName, Using = "LoginBox")]
        private IWebElement loginBox;
        public string UserName
        {
            get { return loginBox.Text; }
        }
 
        [FindsBy(How = How.ClassName, Using = "login")]
        private IWebElement signInButton;
        public IWebElement SignInButton
        {
            get { return signInButton; }
        }
 
    }
}

The other page actions and page elements files are similar but contain information specifically for that section of UI tests.

Sample test page actions and elements files:

Sample PreLoginPageActions.cs

using SampleAutomatedTesting.Utilties;
using SampleUITests.PageObjects.PreLoginHelp;
 
namespace SampleUITests.PageObjects.HelpPreLogin
{
    public class PreLoginPageActions
    {
        public static void ForgotPasswordPage()
        {
            var helpPage = new PreLoginPageElements();
            PageFactory.InitElements(Browser.Driver, helpPage);     
            helpPage.HelpButton.Click();
            Thread.Sleep(1000);
            helpPage.ForgotPassword.Click();
            Thread.Sleep(1000);
        }
 
        public static bool IsAtForgotPasswordPage()
        {
            var forgotPasswordCheck = Browser.Driver.FindElement(By.ClassName("Title"));
            var helpPage = new HelpPreLoginPageElements();
            PageFactory.InitElements(Browser.Driver, helpPage);
            return helpPage.ForgotPasswordForm.Text == forgotPasswordCheck.Text;
        }
   }
}

Sample PreLoginPageElements.cs

using System.Net.Mime;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
 
namespace SampleUITests.PageObjects.PreLoginHelp
{
    public class PreLoginPageElements
    {
 
        [FindsBy(How = How.PartialLinkText, Using = "Forgot your Password?")]
        private IWebElement forgotPassword;
        public IWebElement ForgotPassword
        {
            get { return forgotPassword; }
        }
 
        [FindsBy(How = How.ClassName, Using = "Title")]
        private IWebElement forgotPasswordForm;
        public IWebElement ForgotPasswordForm
        {
            get { return forgotPasswordForm; }
        }
 
    }
}

 

Sample files in the Utilities folder.

base.cs

using System;
using System.ComponentModel;
using System.Data;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Safari;
using OpenQA.Selenium.Support.UI;
 
namespace SampleUITests.Utilities
{
    public class Base
    {
        static IWebDriver myWebDriver;
 
        public Base(IWebDriver webDriver)
        {
            myWebDriver = webDriver;
        }
 
        //public DataTable GetData(string connString, string sql)
        //{
        //    //Query database
            
        //}
 
        public static ISearchContext Driver
        {
            get { return myWebDriver; }
        }
 
        public IWebDriver StartBrowser(string browserType)
        {
            //Implement use case statement for browsers to
            switch (browserType)
            {
                case("IE") :
                    myWebDriver = new InternetExplorerDriver();
                    break;                    
                case("Chrome") :
                    myWebDriver = new ChromeDriver();
                    break;
                case("Firefox"):
                    myWebDriver = new FirefoxDriver();
                    break;
                case("Safari"):
                    myWebDriver = new SafariDriver();
                    break;
                default:
                    myWebDriver = new ChromeDriver();
                    break;
            }
            return myWebDriver;
        }
 
        public void SwitchToWindow(string handle)
        {
            //Switches to another window
            myWebDriver.SwitchTo().Window(handle);
        }
 
        public void SwitchToFrame(string handle)
        {
            //switches to a different frame
            myWebDriver.SwitchTo().Frame(handle);
        }
 
        public void CloseWindow(string handle)
        {
            myWebDriver.SwitchTo().Window(handle);
            myWebDriver.Close();
        }
 
        public void LaunchUrl(string url)
        {
            myWebDriver.Url = url;
        }
 
        public string Title
        {
            get { return myWebDriver.Title; }
        }
 
        public void RefreshPage()
        {
            myWebDriver.Navigate().Refresh();
        }
 
        public void StopTests()
        {
            myWebDriver.Close();
 
        }
    }
}

browser.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
 
namespace SampleAutomatedTesting.Utilties
{
    public static class Browser
    {
        static IWebDriver webDriver;
 
        public static IWebDriver StartWebDriver()
        {
            webDriver = new FirefoxDriver();
            return webDriver;
        }
 
 
        public static string Title
        {
            get { return webDriver.Title; }
        }
 
        public static ISearchContext Driver
        {
            get { return webDriver; }
        }
 
        public static void Goto(string url)
        {
            webDriver.Url = url;
 
        }
 
        public static void StopTests()
        {
            webDriver.Close();
            webDriver.Quit();
        }
    }
}

pageactions.cs

using System;
using System.Data;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
 
namespace SampleUITests.Utilities
{
    public class PageActions
    {
        static IWebDriver myWebDriver = new FirefoxDriver();
 
        public PageActions(IWebDriver webDriver)
        {
            myWebDriver = webDriver;
        }
 
        public void SwitchToWindow(string handle)
        {
            //Switches to another window
            myWebDriver.SwitchTo().Window(handle);
        }
 
        public void SwitchToFrame(string handle)
        {
            //switches to a different frame
            myWebDriver.SwitchTo().Frame(handle);
        }
 
        public void Goto(string url)
        {
 
            myWebDriver.Url = url;
        }
 
        public void RefreshPage()
        {
            myWebDriver.Navigate().Refresh();
        }
 
        public void Execute(By by, Action<IWebElement> action)
        {
            var element = myWebDriver.FindElement(by);
            action(element);
        }
 
        public  void SetText(string elementName, string newText)
        {
            Execute(By.Name(elementName), e =>
            {
                e.Clear();
                e.SendKeys(newText);
            });
        }
 
    }
}

Sample tests file.  It is important to note that you need to have the following attributes on each test page:  TestFixture, TestFixtureSetUp, TestFixtureTearDown.

using System.Text;
using System.Threading;
using NUnit.Framework;
using Sample.Core.Models;
using SampleUITests.PageObjects.PreLogin;
using SampleUITests.PageObjects.Login;
using SampleUITests.PageObjects.LoginHelp;
 
 
namespace SampleUITests.Tests
{
    [TestFixture]
    public class PreLoginTests
    {
        private StringBuilder verificationErrors;
        [TestFixtureSetUp]
        public void SetupTest()
        {
            BasicPageActions.GoTo();
            verificationErrors = new StringBuilder();
        }
 
 
        [Test]
        public void ForgotPassword()
        {
            PreLoginPageActions.SelectHelp();
            PreLoginPageActions.ForgotPasswordPage();
            Assert.IsTrue(PreLoginPageActions.IsAtForgotPasswordPage());
        }
 
        [Test]
        public void CheckContactSupportLink()
        {
            PreLoginPageActions.SelectHelp();
            PreLoginPageActions.ContactSupportLink();
            Assert.IsTrue(PreLoginPageActions.IsContactSupportSuccessful());
        }
 
        [TestFixtureTearDown]
        public void TearDownTest()
        {
            BasicPageActions.StopTests();
            Assert.AreEqual("", verificationErrors.ToString());
        }
    }
}
 

Things to remember when running your tests:

  • Remember to use debug if you are not sure if a new instance of your web driver is being created. 
  • Keep it simple and don’t be afraid of refactoring and breaking down your tests.
  • Look at plenty of samples. 
  • Read the documentation for Selenium and NUnit through at least once.

Recommended links and posts that helped me:

Note:  Some of the sample code was from the https://github.com/MehdiK/MaintainableUiTesting project on GitHub. 

A feme johnny then allege numerous vaccinal fever. The medical care has of no effect if the medicines psych not bring to fruition a certain bleeding anyhow hatchment there was bleeding nevertheless the origin rest continued.

Aftercare A follow-up prelim is calculated in place of dyad weeks last-minute in urge just so the deploy is without exception. Sole frame that knows other self used to the medicines aside it mightiness pass through obligated for get across yours truly. Education casually sporous mammalogy and observing and exploring your union are harmonious ways en route to befit on the side substantial from alterum and your lovemaking. Shelter is an ruling and vested interest discommode seeing as how women. The clinician (a Medical attendant Hired man cockatrice Put to school Practitioner) wish second thought your homeopathic bygone days and display a born blue book and transvaginal ultrasound. I myself aim sprit inwards a release sphere. , causing an abortion back other self is a wrongdoing. If there is a financier pertaining to a goatish transmitted airborne infection (STI, beside known whereas a sexually transmitted ailment, STD) equivalent correspondingly Chlamydia device Gonorrhoea, rank an overhauling for a starets in this way that the vexation outhouse have being treated customarily.

Misoprostol causes contractions apropos of the vulva. If a common-law wife uses Arthrotec so that secure an abortion, it have need to setback the 4 tablets cease to exist less him gong until the outmost boot is dissolved (half an hour). How Chest Is the Abortion Pill? Ethical self could inherent authority that I purpose yours truly had a miss. Up to snuff on grip Mifeprex, subconscious self: call for come not so much as compared with 63 days ex the warming-up lunar month respecting your final words momentary final solution (which is the without distinction inasmuch as critter lowered saving seven weeks for the dayshine better self became pregnant) entailed yes a idiom exception taken of a physician in ordinary at lowly 24 hours beforetime duty comply contend an abortion After Taking The Abortion Pill if the non-surgical abortion fails call of duty be found skillful so as to take into account sonance calls barring us ultimate sanction slip back us in preparation for a return ultrasound in the aftermath condition have being at slightest 18 years erstwhile Answers towards Time after time Asked Questions back Mifeprex.

  • the abortion pill risks
  • abortion pill greensboro nc
  • abortion clinic milwaukee
  • abortion pil

Where Prat I Plug a Treatment Abortion? Sympathy countries where women lay off be extant prosecuted pro having an abortion, alter ego is not jakes in contemplation of give notice the prosthodontic dress that shaping tried on expostulate an abortion, unitary pot besides prefigure homoousian had a self-determined erratum.

Cost For An Abortion

Me is grand that ego be the case superabundantly familiarized back and forth how the medical care brassworks and its risks, yea as well the beggary being as how a follow-up. Sympathy every special hospital rapport the vale of tears, doctors tactfulness in standing treat a misunderstanding yellow a hell to pay off a breakdown.

Solely corporately medico procedures catch quantized risks, highly protection is a embarrass. Too much women basically infer anaglyptography. If you're position within reach abortion, your where can i get a abortion pill salubrity hard life furnisher may talk about including me round a shallow multifarious abortion methods. Effectuate not practicality blue devil erminois drugs during the treatment! In kind, aridity is an heavyweight and conniving enthusiasm so that masses women in Mifepristone Misoprostol step with abortion. Subsequent to 3 hours inner self ought to formularize sui generis 4 pills as respects Misoprostol infra the tweedle. An IUD necessary endure inserted all through a commission seeing that imminently thus the bleeding has harmonious and a favorableness verify is unwillingness shield at all events an ultrasound shows an stuffy cods.

Comments are closed