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#.

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;

//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.

namespace ConsoleApplication1
    class FirstWebDriverScript
        static void Main(string[] args)
           //Declaration of application related variables.
            String _baseUrl = "";
            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 page

            //Maximizing the browser Window
            //Searching for the Google Search box by using XPath
            IWebElement _googleSearch = idriver.FindElement(By.XPath(_boxGoogleSearch));
            //Entering the search string in Google Search Box
            //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

            //Releasing all application-defined tasks with freeing, releasing, or resetting unmanaged resources.

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


Post a Comment

Back To Top