Tuesday, September 20, 2011

How to run Selenium Webdriver code with Visual Studio Test Framework

 

Previous Post, I have shown you how to run selenium WebDriver code in Visual Studio with NUnit Framework.

Now I will show you how Selenium WebDriver code generated from selenium IDE can be run at Visual studio Test Framework.

Selenium IDE has a functionality to convert its recorded script to Selenium WebDriver and C# in NUnit Framework. Here we copy some portion of code and paste it to Visual studio test framework

So If we know how to record Selenium IDE (see the post : http://bit.ly/pa1TG5) then we can easily convert it to selenium WebDriver code.

Before starting we just define a Test case.

Test case :

    1. Open Selenium Website (http://seleniumhq.org/) in Firefox browser.
    2. Click Project tab
    3. Click Selenium IDE link
    4. Verify that Selenium IDE Text is present

Step 1: Record the test case in Selenium IDE

  • Open Firefox Browser
  • Open Selenium IDE window by Clicking Tools->Selenium IDE
  • Make Red colored Record button on.
  • Enter the URL : http://seleniumhq.org/ at the address bar and click Search button
  • Click Project tab
  • Click Selenium IDE link
  • Verify that Selenium IDE Text is present

The recorded script will be like the following figure

se9_thumb

Now make the record button off and Click Run button to run the script.

Step 2: Convert the Selenium IDE recorded script to C# WebDriver code

  • Go to Selenium IDE window
  • Click Options menu
  • Click Format –> C#(WebDriver).

se10_thumb2

Sometimes in Options –> Format menu, C#(WebDriver) options may not be displayed. The menu options like:

se13_thumb[1]

In that case, there is some change needed in selenium IDE option window. Please follow the steps:

  1. Click Options menu in Selenium IDE window
  2. Click “Options…” and Selenium IDE options window is displayed.

se12_thumb

se14_thumb1

Click Enable experimental features check box and click OK button. Now go to Format options and driver list.

  • A message dialog is displayed after selecting the appropriate format like (C#(WebDriver))

se11_thumb

  • Click OK button
  • Selenium IDE window shows the selenium WebDriver Code in C# format with unit testing Framework NUnit is implemented.

se15_thumb3

Step 2: Run the Code in visual Studio 2010 Test Framework

  • Open Visual Studio 2010 IDE
  • Create a Test Project by Clicking Test->New Test. A Test project is created with a default class name UnitTest1.cs
  • Double click on UnitTest1.cs on Solution Explorer to open the class file

se25

  • Now go to Selenium IDE code editor and find the method name “TheUntitledTest()”
  • Copy the entire code of this method and paste to “TestMethod1()” method of VS Test project and the method “TestMethod1()” looks like the following

 

public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            driver.Navigate().GoToUrl(baseURL);
            driver.FindElement(By.LinkText("Projects")).Click();
            driver.FindElement(By.LinkText("Selenium IDE")).Click();
            // ERROR: Caught exception [ERROR: Unsupported command [isTextPresent]]
        }
    }

 

  • Now Add two selenium namespace

 

  1. using OpenQA.Selenium;
  2. using OpenQA.Selenium.Firefox;

 

  • Now go to selenium download page ( http://seleniumhq.org/download/ ) and download the latest version of Selenium Client Driver with C#. Here version 2.6.0 is downloaded.

se17_thumb3

  • Now unzip downloaded zip file and rename the folder as “Selenium”
  • Go to Solution explorer of Visual Studio IDE
  • Right click Reference and click Add Reference option. Add Reference window is displayed

se19_thumb1

  • Click Browse tab and go to Selenium folder. Inspect that there are 2 sub folder – net35 and net40. net35 folder is for .Net framework 3.5 project and net40 for .Net framework 4.0 project. In this project .Net framework 4.0 is selected so we go to net40 folder
  • Select all the dlls and click OK button and .dll files are added as reference

se20_thumb3

 

  • Now all the references are added
  • Go to “public void TestMethod1()” method
  • Create Firefox Driver object named “driver” and the code will be
FirefoxDriver driver = new FirefoxDriver();
  • Add a string variable for base URL named “baseURL”.  Code looks like
string baseURL = "http://seleniumhq.org/";

 

  • Add the following code at the TestMethod1() method for verification

Assert.AreEqual(driver.FindElement(By.XPath("//div[@id='mainContent']/table/tbody/tr/td/p/b")).Text, "Selenium IDE");
  • For closing the browser window add the code at last line
driver.Close();
  • Here is the total code for VS Test
      using System;
      using System.Text;
      using System.Collections.Generic;
      using System.Linq;
      using Microsoft.VisualStudio.TestTools.UnitTesting;
      using OpenQA.Selenium;
      using OpenQA.Selenium.Firefox;

      namespace TestProject1
      {
          [TestClass]
          public class UnitTest1
          {
              [TestMethod]
              public void TestMethod1()
              {
                  FirefoxDriver driver = new FirefoxDriver();
                  string baseURL = "http://seleniumhq.org/";
                  driver.Navigate().GoToUrl(baseURL);
                  driver.FindElement(By.LinkText("Projects")).Click();
                  driver.FindElement(By.LinkText("Selenium IDE")).Click();
                  Assert.AreEqual(driver.FindElement(By.XPath("//div[@id='mainContent']/table/tbody/tr/td/p/b")).Text, "Selenium IDE");
                  driver.Close();
              }
          }
      }
       
      • Build the solution by right clicking on the solution name and Click build solution
      • Inspect that no Error message is displayed and build is succeeded.
      • Click Run button
      • Firefox Browser is opened and Script runs and Test is successful.

      se26

      That’s all. I have described here all the steps in a very easy and details way. If any thing could not understand, please comment me, I must answer.

      In my next Selenium blog, I will show how we can run our selenium WebDriver code in Java with JUnit4 Framework.

    • 27 comments:

      1. Hi Nadim,

        Thanks for your blog article. Really helpful to me.I have a question, if you can help me with..When I do some action, say click event the page posts back (loads) and my test fails. Is there any way we can use clickAndWait or WaitForPageLoad as in IDE? Your response will be highly appreciated!

        Thanks,
        Tester

        ReplyDelete
        Replies
        1. Use the Wait class to wait for a specific element to appear. This class simply calls findElement over and over, discarding the NoSuchElementException each time, until the element is found (or a timeout has expired)

          Delete
      2. I have done something similar also
        http://amir-shenodua.blogspot.com/2012/04/running-selenium-tests-from-visual.html

        ReplyDelete
      3. Hi Nadim
        i've done all as you show , but getting this error while running the test ,
        can you help ?

        Test method TestProject1.UnitTest1.TestMethod1 threw exception:
        System.IO.FileNotFoundException: Could not load file or assembly 'WebDriver, Version=2.21.0.0, Culture=neutral, PublicKeyToken=1c2bd1631853048f' or one of its dependencies. The system cannot find the file specified.=== Pre-bind state information ===
        LOG: User = yaniv-Laptop\yaniv
        LOG: DisplayName = WebDriver, Version=2.21.0.0, Culture=neutral, PublicKeyToken=1c2bd1631853048f
        (Fully-specified)
        LOG: Appbase = file:///c:/users/yaniv/documents/visual studio 2010/Projects/TestProject2/TestProject2/bin/Debug
        LOG: Initial PrivatePath = NULL
        Calling assembly : TestProject2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.

        Thanks

        ReplyDelete
      4. Hi Nadim,

        I'm am running this as a web based application, it builds perfectly, but when I hit debug my browser comes up with the following error: "Server Error in '/' Application."
        Parser Error
        Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
        Parser Error Message: Only Content controls are allowed directly in a content page that contains Content controls.

        Is there a workaround?

        ReplyDelete
      5. Can you elborate more steps on how to run the unit test of C# code in selenium webdriver , with VS2010.

        ReplyDelete
      6. Create a Test Project by Clicking Test->New Test. i didnt get this menu bar in visual studio..plz help me

        ReplyDelete
      7. Thanks Nadim. This has been really helpful...

        ReplyDelete
      8. Thanks for your blog. I am able to follow your instruction to make a test run. I would like to know if it is possible to make test project as executable. That can be installed on tester computer.

        ReplyDelete
      9. Thank you very much, it helped me a lot!

        ReplyDelete
      10. Can we use web driver without ID and Xpath's but only with multiple class names...?

        ReplyDelete
      11. Hi Nadim,

        Thank you very much for this article.
        Good start for me.

        ReplyDelete
      12. Really nice topics you had discussed above. I am much impressed. Thank you for providing this nice information here

        Software Testing Company

        Console Game Testing

        Game Testing Company

        Video Game QA

        ReplyDelete
      13. The article seems to be more informative. This is more helpful for our selenium training in chennai Thanks for sharing

        ReplyDelete