zoukankan      html  css  js  c++  java
  • Selenium资料

     
    ARTICLE
     

    Data Driven Testing Using Selenium (webdriver) in C#

    Posted by Jawed MD  Articles | Visual C#  February 07, 2012
     
    In this article, I would like to explain about performing data driven testing in Selenium using .Net.
     
     
    Reader Level:
     
    Download Files:
    • AutomationUsingSeleniumTest.zip
     

     In this article, I would like to explain about performing data driven testing in Selenium. 

    I have used C# language and for IDE is Visual Studio 2010 Ultimate edition to achieve our aim. As we will proceed we will know, step by step how to Create a Data Driven Test method using Selenium in .Net. So for now, let's roll our sleeve and get going.

    Before going into details, it would be better to provide a synopsis of a few things so that even you can become familiar with everything. And as I will proceed you will not feel cut off from the main theme. 

    Selenium

    Selenium is a portable software testing framework for web applications. Selenium provides a record/playback tool for authoring tests without learning a test scripting language (Selenium IDE). It also provides a test domain-specific language (Selenese) to write tests in a number of popular programming languages, including C#, Java, Groovy, Perl, PHP, Python and Ruby. The tests can then be run against most modern web browsers. Selenium deploys on Windows, Linux, and Macintosh platforms.

    (Source: http://en.wikipedia.org/wiki/Selenium_(software))

    I will refrain from going into details about Selenium. Since there is tons of documentation and information available on the internet which already explain Selenium. You can go through over there.

    You can visit the Selenium official website for the documentation:

    http://seleniumhq.org/ 

    Download the Selenium for .Net from here:

    http://seleniumhq.org/download/

    Apart from that you can visit my blog also to get to know the Selenium web driver using .Net.

    http://seleniumdotnet.blogspot.com/.

    Data Driven Testing

    Data driven testing is an action through which a set of test input and/or output values are read from data files (ODBC source, CSV files, Excel files, DAO objects, ADO objects etc) and are loaded into variables in captured or manually coded script. Data-Driven testing generally means executing a set of steps with multiple sets of data. Selenium does not provide any out-of-the box solution for data driven testing but leaves it up to the user to implement this on his own. That is why we are here; to do out of box.

    Code:

    Prerequisites

    • Visual Studio 2010 Premium or Visual Studio 2010 Ultimate.

    So now our main coding will start from here:

    We will be using the Unit testing feature provided by VS2010 and C# code for the same.

    1. Select Unit test as project from VS2010

      1.1 Open your VS2010
      1.2 Click on the Test Tab and select New test



      1.3 Click on Unit test from the New open window 



      Figure1. Select Unit Test from VS2010

      1.4 Rename the File to SeleniumTest.cs
       
    2. Add Selenium web driver references

      2.1 Add the following dlls through add references:



      Figure2. Add Selenium DLL in the project.
       
    3. Open the selenium.cs file and add the following Name space:

       
      using OpenQA.Selenium; 
      using OpenQA.Selenium.IE;
      //add this name space to access WebDriverWait
      using OpenQA.Selenium.Support.UI;
      Never try to add this forcefully unless you are not getting it with your VS intelligence.
    Test Initialization:

      public static IWebDriver WebDriver;
      // Use TestInitialize to run code before running each test 
      [TestInitialize()]
      public void MyTestInitialize()
      {
        var capabilitiesInternet = new OpenQA.Selenium.Remote.DesiredCapabilities();
        capabilitiesInternet.SetCapability(
    "ignoreProtectedModeSettings"true);
        WebDriver = 
    new InternetExplorerDriver(capabilitiesInternet);
       }
    Test CleanUp

      // Use TestCleanup to run code after each test has run
      [TestCleanup()]
      public void MyTestCleanup()
      {
         WebDriver.Quit();
      }

    Before implementing the test method for data driven we will write the Selenium Test method without Data Driven. Then we will go for Data Driven Testing, by doing this scenario you will clearly understand the difference between a simple Selenium test method without data driven and Selenium test method with Data Driven.

    Selenium Test Method without Data Driven

    To write Automation code using Selenium to automate our target website we will use any web application. Here I will use a http://www.x-rates.com/calculator.html web application for our AUT (Application under Test) purpose. The function of this AUT web application is to compare a currency value from one country's currency to another country's currency.

    NOTE: The AUT website is just for demo purposes. The currency rate would not be fixed. So perhaps the test cases pass for me but would fail for you or vise-versa.

    The web page is as below:



    Figure 3. Application Under test

    Now we will write our Selenium Test method to perform the following operation:
    1. Select Value into the first dropdown box (convert)
    2. Select value into the second dropdown box (into)
    3. Click on the Calculate button to get the currency value w.r.t first country's currency selected.
    4. Read the value from upper textbox/input box. This will be our actual result.
    5. Compare the actual value from the expected value.

       
       [TestMethod]
              public void TestCurrencyConvertorWithoutDDT()
              {
                 //Read your first country currency name
                  var convertVal = "American Dollar";
                  //Read your second contry currency
                  var inToVal = "Indian Rupee";
                  //Read Expected value from data source
                  var expectedValue = "49.7597 INR";
                  //Goto the Target website
                  WebDriver.Navigate().GoToUrl("http://www.x-rates.com/calculator.html");
                  var setValueConvert = WebDriver.FindElement(By.Name("from"));
                  var setValueInto = WebDriver.FindElement(By.Name("to"));
                  var calculateButton = WebDriver.FindElement(By.Name("Calculate"));
                  var outPutvalue = WebDriver.FindElement(By.Name("outV"));
                  var selectConvertItem = new SelectElement(setValueConvert);
                  var selectIntoItem = new SelectElement(setValueInto);
                  selectConvertItem.SelectByText(convertVal);
                  selectIntoItem.SelectByText(inToVal);
                  calculateButton.Click();
                  var currencyValue = outPutvalue.GetAttribute("value");

                  Thread.Sleep(900);//Not a good practise to use Sleep
                  //Get the screen shot of the web page and save it on local disk 
                  SaveScreenShot(WebDriver.Title);
                  Assert.AreEqual(expectedValue, currencyValue.Trim());
             }


    Run the above Test method to see the result:
    1. On the Test menu, click Windows and then select Test View.



      Figure 4. Select Test View

      The Test View window is displayed.



      Figure 5. Test View Window
       
    2. Right-click TestCurrencyConvertorWithoutDDT and click Run Selection. 

      If the Test Results window is not already open, it opens now. The TestCurrencyConvertorWithoutDDT test runs.

      In the Result column in the Test Results window, the test status is displayed as Running while the test is running. 
       
    3. In the Test Results window, right-click the row that represents the test and then click View Test Results Details.



      Figure 6. Test Results Windows


    Test Method as Data Driven

    As you have already seen in the above Selenium test method we ran our method for only one set of values. Now in Data Driven we will run the same method with multiple sets of inputs value.

    To read the input values against which we are going to run our Test method, we have stored our input values into a data Source. For that we will use a CSV file, but you can also use other data sources such as Excel Sheet etc. 
    In this CSV file we will store our expected result also so that we can compare our actual output with this value.

    Our csv will look something like this (give the name to this csv file as DDT.csv):



    Figure 7. CSV file as Data Source

    Now we will connect the above Test method to our data Source [here it is DDT.CSV]
    1. Open the solution that contains the test method for which you want to use a data source.
    2. On the Test menu, point to Windows, and then click Test View.
    3. In the Test View window, right-click the unit test for which you want to use a data source and then click Properties.



      Figure 8. Properties of Selenium Test Method
       
    4. In the Properties window click Data Connection String and then click the ellipses(…).



      Figure 9. Test Data Source Wizard
       
    5. Follow the instructions in the in the New Test Data Source Wizard to create the data connection.

      A connection string is added to your unit test after the first bracket of the [TestMethod()] element.

      It would be something like this:
       
       [DeploymentItem("AutomationUsingSeleniumTest\DDT.csv"),DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\DDT.csv", "DDT#csv",DataAccessMethod.Sequential)]
       
    6. Now we will assign variables to values from your data source

      6.1 Open the Test file that contains the test method for which you want to use a data source and locate the variables in the test method.

      6.2 For each variable that you want to come from the data source, use the syntax TestContext.DataRow["NameOfColumn"].

      The piece of code would be as below:
       
      //Read your first country currency name
      var convertVal = TestContext.DataRow["FirstCountryByText"].ToString();
      //Read your second contry currency
      var inToVal = TestContext.DataRow["SecondCountryByText"].ToString();
      //Read Expected value from data source
      var expectedValue = TestContext.DataRow["ExpectedValue"].ToString();

      The whole Code of the Test Method would be as below:

       
       DeploymentItem("AutomationUsingSeleniumTest\DDT.csv"),DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\DDT.csv", "DDT#csv",DataAccessMethod.Sequential)]
            [TestMethod]
            public void TestCurrencyConvertorWithDDT()
            {
                //Read your first country currency name
                var convertVal = TestContext.DataRow["FirstCountryByText"].ToString();
               //Read your second contry currency
                var inToVal = TestContext.DataRow["SecondCountryByText"].ToString();
                //Read Expected value from data source
                var expectedValue = TestContext.DataRow["ExpectedValue"].ToString();
                //Goto the Target website
                WebDriver.Navigate().GoToUrl("http://www.x-rates.com/calculator.html");
                var setValueConvert = WebDriver.FindElement(By.Name("from"));
                var setValueInto = WebDriver.FindElement(By.Name("to"));
                var calculateButton = WebDriver.FindElement(By.Name("Calculate"));
                var outPutvalue = WebDriver.FindElement(By.Name("outV"));

                var selectConvertItem=newSelectElement(setValueConvert);
                var selectIntoItem =newSelectElement(setValueInto);
               selectConvertItem.SelectByText(convertVal);
                selectIntoItem.SelectByText(inToVal);
                calculateButton.Click();
                var currencyValue =outPutvalue.GetAttribute("value");
                Thread.Sleep(900);//Not a good practise to use Sleep
                //Get the screen shot of the web page and save it on local disk 
                SaveScreenShot(WebDriver.Title);
               Assert.AreEqual(expectedValue,currencyValue.Trim());
            }

       
    7. Run the Test Method (I already explained this) and the Result will be something like below:



      Figure 10. Data Driven Test Results

      So you can clearly see that the Test method has ran for 4 different sets of values. And it fetched the input values from our specified data source; that is DDT.csv.

    Download the code to get the whole piece of code. I have used a method that is SaveScreenShot(WebDriver.Title). You can get the code details along with the uploaded code. Actually this method would take the screen shot of your target web page and will store that in the Test Result directory. 

    Save Screen Shot Method
    /// <summary>
    /// This will Take the screen shot of the webpage and will save it at particular location
    /// </summary>      ///
    <param name="screenshotFirstName"></param>
    private static void SaveScreenShot(string screenshotFirstName)
    {
        var folderLocation = Environment.CurrentDirectory.Replace("Out","\ScreenShot\");
        if (!Directory.Exists(folderLocation))
        {
            Directory.CreateDirectory(folderLocation);
        }
        var screenshot = ((ITakesScreenshot)WebDriver).GetScreenshot();
        var filename = new StringBuilder(folderLocation);
        filename.Append(screenshotFirstName);
        filename.Append(DateTime.Now.ToString("dd-mm-yyyy HH_mm_ss"));
        filename.Append(".png");
        screenshot.SaveAsFile(filename.ToString(), System.Drawing.Imaging.ImageFormat.Png);
    }
     

    The Screen shot of your Target web page will be saved as below:



    Figure 11. Screen Shot saved at Test Result folder.

    Feel free to provide your valuable feedback and comments!!

    For any issue/question/suggestion in Selenium for C# you can refer to this blog: http://seleniumdotnet.blogspot.com/ 
     
     
     
     
    COMMENTS
     
     
    View Previous Comments
     
     
    sandeep qa
    Hello Jawad.. Can you post blog regardig to Login page test case .. DDtest with C#. Thanks... Sandeep.
    Aug 17, 20120 Like0 Reply
     
     
    Saravanan Nallamuthu
    Hi jawad, The Example is nice I need to execute a test case using .NET Say i have the following steps Step1:Enter value for Name Texbox Step2:Enter value for Phone Textbox Step3:Click on the Submit button. And in the Excel i will have By.id('TXT_NAME').SendKeys('Value1'); By.Id('TXT_Phone').SendKeys('Valu2'); By.id('BTN_Submit').Click(); How can i execute the test case using the Data Driven framework. The Example that you have given is a kind of iteration where i can enter all possible values for Name textbox and Phone Textbox Can you help on this
    Sep 15, 20120 Like0 Reply
     
     
    Huong Pham
    Hi Jawed,Thanks much for sharing this tutorial :) But when following your steps,I meet a problem "An object reference is required for the non-static field, method, or property'Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.DataRow.get'" I tried this code "var amountToConvert=System.Convert.ToString(TestContext.DataRow["Vamoun"])",It still doesn't work.Could you help me to solve it.Thanks.
    Oct 17, 20120 Like0 Reply
     
     
    evan sun
    add below property will avoid this issue: "An object reference is required for the non-static field, method, or property public TestContext TestContext { get; set; }
    Nov 28, 20120 Like0 Reply
     
     
    Jawed MD
    Thank you so much for your comments and suggestion!!
    Jan 22, 20130 Like0 Reply
     
     
    titi lope
    Hello Guys, I am getting error on this line var capabilitiesInternet = new OpenQA.Selenium.Remote.DesiredCapabilities(); capabilitiesInternet.SetCapability("ignoreProtectedModeSettings", true); WebDriver = new InternetExplorerDriver(capabilitiesInternet); Error 1 The best overloaded method match for 'OpenQA.Selenium.IE.InternetExplorerDriver.InternetExplorerDriver(string)' has some invalid arguments unless I have to pass the path to the IEDriverServer.exe as below which is a problem for me because I cannot set all the zones to the same value on my IE Security tab for some reasons. IWebDriver driver = new InternetExplorerDriver(@"C:DownloadIEDriverServer"); I am using selenium-dotnet-2.32.0 Webdriver assembly. Please any idea on why I am getting this error or what I am missing? Thanks lope
    Apr 24, 20130 Like0 Reply
     
     
    Mukur Chaudhuri
    hi
    Jun 04, 20130 Like0 Reply
     
     
    Mukur Chaudhuri
    hi i need help...i have a website and i want to access passwords from excel file and check logins automatically in my code...how do i access the passwords one by one from my excel sheet directly
    Jun 04, 20130 Like0 Reply
     
     
    Mahesh Upadhyay
    Hi Jawed, I saw your blog, which exceptional. You did a fantastic job. I have a question on selenium webdriver, 1. Did you use any reporting structure for selenium except than assert.fail/pass? If yes, can you please share your code with me it will be great help for me. 2. How come I wait till I check if webelement are exist on the page? Currently I m using wait.Until(ExpectedConditions.ElementExists(By.Name("UserID"))); 3. Do you use any user interface where you can select the test cases that you want to run and just click run. It will execute all selected selenium test cases? Please share you view if you have the same. Please see if you can help me out. Thanks, Mahesh Upadhyay
    Jun 05, 20130 Like0 Reply
     
     
    Mahesh Upadhyay
    Hi Jawed, It is not generated the visual studio solution under Out folder in Test results, can you please let me know the exact solution for tghis
    Jun 05, 20130 Like0 Reply
     
     
     
     
    COMMENT USING
     
     
    PREMIUM SPONSORS
     
     
    Nevron Software is a global leader in component based data visualization technology for a diverse range of Microsoft centric platforms. Nevron Data Visualization components are used by many companies, educational and government organizations around the world.
     
     
     
     
     
    Tags
    SPONSORED BY
     
     
     
    POLLRESULTALL POLLS
     
    Windows 8
     
    What is your status with Windows 8?
     
       
     
     

  • 相关阅读:
    使用hadoop平台进行小型网站日志分析
    flume分布式日志收集系统操作
    map-reduce任务的执行流程
    linux设置定制器自动执行任务
    pig笔记
    hive操作记录
    hbase集群安装和shell操作
    Spark Streaming揭秘 Day24 Transformation和action图解
    Spark Streaming揭秘 Day23 启动关闭源码图解
    Spark Streaming揭秘 Day22 架构源码图解
  • 原文地址:https://www.cnblogs.com/wcLT/p/3409971.html
Copyright © 2011-2022 走看看