Monday, 30 September 2013

WebDriver Script in C#

Guru(s)/Reader(s), we have seen the introduction of Web Driver and its installation with C# in my previous articles. Now, we are going to code our First Web Driver Script in C#.

Requirement:
01.Navigate to Google Home page.
02.Enter some Url in the Search box.
03.Verify the result.
04.Close the browser before ending the entire program.



WebDriver Code: 
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;

#region
//OpenQA.Selenium - Contains the WebDriver class needed to instantiate a new browser loaded with the specific browser. Here we used, Firefox browser.
//OpenQA.Selenium.Firefox - Contains the FirefoxDriver class needed to instantiate a Firefox specific driver onto the browser instantiated by the WebDriver class.
//We can include more namespaces based on our requirement like, manipulating external files,taking screen shots etc.
 #endregion

namespace ConsoleApplication1
{
    class FirstWebDriverScript
    {
        static void Main(string[] args)
        {
           //Declaration of application related variables.
            String _baseUrl = "http://www.google.com";
            String _boxGoogleSearch = ".//*[@id='gs_htif0']";
           
            //Create a new instance of the Firefox driver,Observe that the above Firefox  class has no parameters. It means that the default Firefox profile will be launched by the program. The default Firefox profile is similar to launching the Firefox in safe mode(i.e., no extensions).
            IWebDriver idriver = new FirefoxDriver();
           
            //Navigate to the Google.com page
            idriver.Navigate().GoToUrl(_baseUrl);

            //Maximizing the browser Window
            idriver.Manage().Window.Maximize();
           
            //Searching for the Google Search box by using XPath
            IWebElement _googleSearch = idriver.FindElement(By.XPath(_boxGoogleSearch));
           
            //Entering the search string in Google Search Box
            _googleSearch.SendKeys("software-testing-community.blogspot.in");
            _googleSearch.Submit();
           
            //Comparing the title with the expected value
            if (idriver.Title.Contains("software-testing-community"))
            {
                Console.WriteLine("Test passed");
            }
            else {
                Console.WriteLine("Test Failed");
            }

           //Closing the Browser
            idriver.Close();

            //Releasing all application-defined tasks with freeing, releasing, or resetting unmanaged resources.
            idriver.Dispose();
           
        }
    }
}

The WebDriver's code and its explanation is included as part of the comments. Please feel free to add your comments/ suggestions.

0 comments:

Post a Comment

 
Back To Top