Tuesday, November 6, 2012

Selenium - Automating UI Testing for Websites using Visual Studio Unit Tests


Selenium is a well-known open source tool for UI automation of websites across a range of browsers. To know more, please refer http://seleniumhq.org/
A huge benefit of using Selenium is that you don’t need an interactive desktop session to run the automated UI tests.
Here we will discuss about integrating Selenium with Visual Studio Unit Tests written in C#
Test
·         Open Bing http://www.bing.com

·         Search for James Bond

·         Verify the results contain a Wikipedia link for James Bond
Steps
·         Download the IE Driver (needed only for running tests in IE) and the C# Client Drivers from http://seleniumhq.org/download/

·         Create a Unit Test Project in Visual Studio using File-New-Project->Test->Test Project

·         Add a folder called Dependencies and add the following files with Copy Always to Output:

o   WebDriver.dll

o   IEDriverServer.exe

o   Ionic.Zip.dll

o   Newtonsoft.Json.dll

·         Add a Reference to WebDriver.dll

·         Make sure Enable Deployment is checked in the Test Settings File, see http://msdn.microsoft.com/en-us/library/ms182475(v=vs.90).aspx

·         Import the following namespaces

using Microsoft.VisualStudio.TestTools.UnitTesting;

using OpenQA.Selenium;

using OpenQA.Selenium.IE;

using System.Drawing.Imaging;

·         Create a Test Class with DeploymentItem Attribute   
[TestClass]
[DeploymentItem("Dependencies\\IEDriverServer.exe")]
public class IETests

·         Create a web driver in Class Initialize and Quit in Class Cleanup
private static InternetExplorerDriver _webDriver;       

[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
            _webDriver = new InternetExplorerDriver(new InternetExplorerOptions() {IntroduceInstabilityByIgnoringProtectedModeSettings = true});

       }
 
[ClassCleanup()]
public static void MyClassCleanup()
       {
            _webDriver.Quit();
       }
 
       private TestContext testContextInstance;    

       public TestContext TestContext
       {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
       } 

·         Create a Test Method
[TestMethod]
       public void TestBing()
       {
            // Test Case Steps
            _webDriver.Navigate().GoToUrl("http://www.bing.com");

            IWebElement search = _webDriver.FindElement(By.Name("q"));

            IWebElement go = _webDriver.FindElement(By.Name("go")); 

            search.SendKeys("james bond");

            go.Click(); 

            // Save screenshot if required
            Screenshot screenshot = _webDriver.GetScreenshot();

            screenshot.SaveAsFile("Result.png", ImageFormat.Png); 

            // Verfication
            IWebElement msWebsite =
                _webDriver.FindElement(
                    By.XPath(

                        "//a[@href='http://en.wikipedia.org/wiki/James_Bond']")); 

            Assert.IsNotNull(msWebsite, "Could not find wikipedia link for James Bond");
       } 

·         To test with Firefox, we can similarly create a Firefox web driver

private static FirefoxDriver _webDriver;

 Troubleshooting
If you see the error Class Initialization method Selenium.IETests.MyClassInitialize threw exception. System.InvalidOperationException: System.InvalidOperationException: Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones. Enable Protected Mode must be set to the same value (enabled or disabled) for all zones. (NoSuchDriver).

This could be if you instantiated the IE Driver using new InternetExplorerDriver()
The fix is to either use new InternetExplorerDriver(new InternetExplorerOptions() IntroduceInstabilityByIgnoringProtectedModeSettings = true})

Or enable Protected Mode setting for all zones. Go to Tools->Internet Option->Security and check “Enable Protected Mode” for all zones.

29 comments:

  1. Hi Anuj, i read your post and found it to be very useful for someone who would like to use dotnet with selenium. Thanks for the wonderful post. I would also like to know how we can generate good quality reports in dotnet for selenium automation test results? Kindly let me know your answer on this.

    ReplyDelete
  2. Glad to know that it was useful. By default if you run these tests in visual studio using mstest, you will get a report for the results. You can also use TFS for running the tests daily and create reports by querying the warehouse, see http://social.technet.microsoft.com/wiki/contents/articles/2061.how-to-create-reports-for-tfs-2010-test-results.aspx

    ReplyDelete
  3. Great post! Does this work with Visual Studio Professional....or does it require VS Premium?

    ReplyDelete
  4. Thanks. It should work if you have unit testing feature which I think comes with Professional version http://www.microsoft.com/visualstudio/eng/products/compare

    ReplyDelete
  5. Hi Anuj, it is work with IE 10 in windows 8 OS

    ReplyDelete
  6. I am not sure about the most common language for selenuim. I agree that it is confusing that so manay languages are available but i would consider this as a plus point considering that you are not bound to just using one language.

    ReplyDelete
  7. Hi anuj,

    Can We Display the two pages in one Web pAge in Selenium.....
    I have a application and its Requires the Two Pages will be displayed in one Page... Any IDeas...??

    ReplyDelete
  8. Hi Viral, I am not sure but may be you can ask this on
    http://docs.seleniumhq.org/support/
    http://www.seleniumforum.com/

    ReplyDelete
  9. Hi Anuj,

    This post talks about Selenium assuming unit tests are defined, what if there are no unit tests and we are starting from scratch using .net & C#.

    So far based on the information available-
    1)we downloaded IE driver & C# Nuget, but did'nt go any further as the documentation available talks about code modification. This is where it got really confusing for me and team. does it mean ( pulling a branch from source control?)
    2) I am a QA with zero experience with Selenium or C# i am very enthused to learn and start this for my current project any direction will is appreciated.

    3) Every one i know are using Selenium with Java

    Thank you

    ReplyDelete
  10. Hi, you can create a unit test project by following the steps mentioned here http://msdn.microsoft.com/en-us/library/hh598957.aspx
    Once you have the unit test project, you can start modifying the code.

    ReplyDelete
  11. Hi Anuj

    Can you train me on csharp and specflow using webdriver .I am reacheable at kalyankc00@gmail.com

    ReplyDelete
  12. I think these forums would be a good place to start exploring these tools and asking questions
    http://docs.seleniumhq.org/support/
    http://www.seleniumforum.com/
    https://groups.google.com/forum/?fromgroups#!forum/specflow

    ReplyDelete
  13. How do we handle windows authentication pop ups using selenium and visual studio??

    ReplyDelete
  14. See if this helps https://groups.google.com/forum/?fromgroups#!topic/selenium-users/WreWTamhpTI

    ReplyDelete
  15. Early in your comments, you specify to: Make sure Enable Deployment is checked in the Test Settings File. It would be useful to give more details about this file, as a new Test Project does not come with it...

    ReplyDelete
  16. Thanks, added a link to provide more details

    ReplyDelete
  17. Hai Anuj....Thanks for the wonderful post...I have a doubt..After creating some website project in Visual studio 2010 say "Login page". How can we perform testing using selenium tool for the "Login page" also what are the things that are to be installed..Can you let us have a clear step by step procedure like msdn.microsoft.com provides. This could be a big favor for us....Because we are very new to testing using selenium tool...

    ReplyDelete
  18. Hi Kodaganti, you can follow the steps similar to what I gave for TestBing(). You can also ask specific questions on selenium on
    http://docs.seleniumhq.org/support/
    http://www.seleniumforum.com/

    ReplyDelete
  19. Hi Anuj,

    First, thanks for your useful post. But I could not file following dll files:
    o Ionic.Zip.dll
    o Newtonsoft.Json.dll
    Could you please give me a link do download it?

    Thanks

    ReplyDelete
  20. Hi Anuj,

    First thanks for your useful post. But I could not find following dll files.
    o Ionic.Zip.dll
    o Newtonsoft.Json.dll
    Could you please give me a link to download them?
    Thanks.

    ReplyDelete
  21. You can find it here https://code.google.com/p/selenium/downloads/detail?name=selenium-dotnet-2.25.1.zip&can=2&q=label%3AFeatured

    ReplyDelete
  22. Hi Anuj Vishal This Side I hope you remember me MSNKOJAX :)

    Please let me know how i can Extract SpecFlow Execution Results report from VSTS 2013
    I am using Specflow + MSTest + Webdriver + VSTS2013

    Thanks
    Vishal

    ReplyDelete
    Replies
    1. I have had problems hgetting anything usefull from Specflow + NUnit; Specflows NUnit report generator just dont work. Instaerd use Specflow own Specrun as your test runner, gives good reports

      Delete
  23. Hey Vishal, I am not sure. Probably you can ask here https://groups.google.com/forum/#!forum/SpecFlow

    ReplyDelete
  24. System.InvalidOperationException: Unexpected error launching Internet Explorer. Could not get document from window handle (NoSuchDriver)

    IWebDriver driver = new InternetExplorerDriver(pathContainingIEDriverServer, new InternetExplorerOptions() { IntroduceInstabilityByIgnoringProtectedModeSettings = true });

    driver.Navigate().GoToUrl("http://www.google.com");

    IWebElement searchTermTB = driver.FindElement(By.Name("q"));
    searchTermTB.SendKeys("jimmy collins blog");

    IWebElement searchBtn = driver.FindElement(By.Name("btnG"));
    searchBtn.Click();

    driver.Close();


    Help

    ReplyDelete
  25. Hi Robert , check your zoom for IE. it should be 100%

    ReplyDelete
  26. Hi Anuj,

    I am new to selenium ui automation.

    I am getting error this "Unable to find element with name == q" for the below.
    IWebElement search = _webDriver.FindElement(By.Name("q"));

    How do I locate UI elements name ? is there a tool like UISPY or something?

    I tried doing viewsource and I saw that the name is "q" but it somehow is throwing this error.

    Thanks!
    Sam

    ReplyDelete
  27. Hi all, two quick comments. There are many ways tgo test web-sites. One recommended way is to use Cucumber (Gherkin based test specification) - See the Cucumber Book. Specflow provides a Visual Studio C# compatible system. Very Mature - agood way to go forward.

    Secondly one of the problems in web-testing is to define locators. There is a great add-on for firefox "Web-driver element locator by andrew". You select a web-elemnt invoke this and select from the choice of methodfs offtered to you. Ecedllent

    ReplyDelete
  28. Nice one Anuj, Informative and well explained. Easily understandable one. Thumps Up!!

    ReplyDelete