Extension Method in Selenium, what, why, and how???

An Extension Method enable us to add methods to existing   types without creating a new derived type, recompile, or modify the original types.

Alright, confusing???

Picture1

Now consider you don’t have access for Car class and if I ask you to add a method for Car class, how would you do that?

In this kind of circumstances you can use Extension method concept to add a method for existing type without creating new class.

Still???

If I ask you write a program which should give today date, probably you would write below lines of code-

Picture2

Now if I ask you to give 1 month back date, probably you would write below method to get 1 month back date-

Picture3

Certainly you would write this method in a class and to call this method you would create object.

Picture4

How it would be if you get same method like this-

Picture5

You can achieve above line of code using Extension Method concept.

Picture6

Now you will see your extension method in below manner-

Picture7

OK, there are some rules also-

  • It should be static method.
  • It must be located in a static class.
  • It should use the “this” keyword as the first parameter with a type in .NET and this method will be called by a given type instance on the client side.
  • An extension method should be in the same namespace as it is used or you need to import the namespace of the class by a using statement.
  • You can give any name for the class that has an extension method but the class should be static.
  • If you want to add new methods to a type and you don’t have the source code for it, then the solution is to use and implement extension methods of that type.

Picture8

Now you will see your selenium extension method in below manner-

Picture9

Alright, now we will see a real time example-

While automating an application sometimes we all observed that click action performs the operation but button does not get clicked.

In that scenario, mostly we write different line of codes or methods to achieve our goal.

So instead of writing code each time for specific click, we can write different extension methods to handle all possible click actions and if one click is not working out we can call another IWebElement click methods (Extension Method).

It’s a right approach in any Automation framework to keep extension methods to perform the similar kind of actions using different ways.

 

How to configure Selenium Grid?

Here I noted down some quick steps to configure Selenium Grid on windows. I am assuming that you are aware about selenium and its features. So here we go-

  • Download Selenium Standalone Jar file from here.
  • Dump it somewhere in host and node machines.
  • Open CMD at Host machine and go to location where you have been dumped the jar file.
  • Now run this command Java –jar seleniumserver-standalone_version.jar –role hub.
  • Now open http://localhost:4444/grid/console.
  • Now go to Node machine.
  • Open CMD at Node machine and go to location where you have been dumped the jar file.
  • Run the below commend if machine is remote-

java –jar selenium-server-standalone_version – role webdriver –hubHost HOST MACHINE NAME – “browserName=iexplorer, platform=WINDOWS” –port 5556

  • Run the below commend if machine is same machine where host is running-

java –jar selenium-server-standalone_version – role webdriver – “browserName=iexplorer, platform=WINDOWS” hubHost http://localhost:4444/grid/register –port 5555

How to run Selenium + TestNG script from Command Line?

This is an alternate way to execute our selenium script from command prompt. Here, I am considering few points-

  • Your project is already set-up in Eclipse
  • Project already has testng.xml file.
  • All selenium and other third party jar files are located under project home folder (lib folder).
  • You are able to execute your script by running testng.xml file.

cmd3

If above conditions are matching then very few steps are there to execute same script from command prompt. Follow the below steps-

Open Command Prompt and Go to Project home directory-

CMD

Set the class path and libraries path by running below command-

set classpath=<Project Home Path>\bin;<Project Home Path>\lib\*

cmd1

Now run the testng.xml file by running below command-

java org.testng.TestNG testng.xml—-Make sure “org.testng.TestNG” TestNG word should have ‘T’ and ‘NG’ in caps.

CMD2

I hope it would help people to run testng.xml file from the command prompt.

EventFiringWebDriver, WebDriverEventListener, and AbstarctWebDriverEventListener

Before getting into the sample code, lets have a look on EventFiringWebDriver, WebDriverEventListener, and AbstarctWebDriverEventListener descriptions.

  • EventFiringWebDriver is a class and wrapper around an arbitrary webdriver instance which supports registering of a WebDriverEventListener.
  • WebDriverEventListener is interface which includes list of abstract events methods and all should be implemented if we are implementing it.
  • AbstarctWebDriverEventListener is abstract class which has implemented WebDriverEventListener interface. We can extend this class if we are only interested in some events. All methods provided by this class have an empty method body.

So we can choose between EventFiringWebDriver and AbstarctWebDriverEventListener according to our needs.

Note: I have used AbstarctWebDriverEventListener class in below example.

Let’s have a look on example-

Create a class file and extends AbstarctWebDriverEventListener class-
public class WebDriverEventListenerClass extends AbstractWebDriverEventListener {
@Override
public void onException(Throwable arg0, WebDriver driver) {

File screenShot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenShot, new File(“c:\\tmp\\exception.png”));
} catch (IOException e) {
e.printStackTrace();
}}}

Create another class file and register WebDriverEventListenerClass file as it has implemented onException event method-

public class EventFiringDriverExample {
@Test
public void Events(){
System.setProperty(“webdriver.ie.driver”, “D:/Training/IE_Driver/IEDriverServer.exe”);

WebDriver driver = new InternetExplorerDriver();

// Creating EventFiringWebDriver instance

EventFiringWebDriver eventFiringDriver= new EventFiringWebDriver(driver);

// Creating instance of eventListener, that we just defined
eventFiringDriver.register(new WebDriverEventListenerClass());

eventFiringDriver.get(“https://www.google.co.in/&#8221;);

eventFiringDriver.findElement(By.className(“nosuchelement”));

}}

Once you run ‘Events()’ method, it will open Google and search for element which is not available. In this case, method will throw WebElementNotFound exception and system will capture the screenshot and save it at “c:\\tmp\\exception.png” location..

How to Launch Chrome browser with Selenium WebDriver?

Before thinking how we can run the our application on Chrome browser, download the ChromeDriver from here.

To lunch chrome browser with Selenium Webdriver takes less than a minute and 3 lines of code. So here we go-

System.setProperty(“webdriver.chrome.driver”, “D:\\Chrome_Driver\\chromedriver.exe”);
WebDriver driver=new ChromeDriver();
driver.get(“http://seleniumeasy.com/&#8221;);

Synchronization or Wait in Selenium WebDriver (C#)

Synchronization or wait helps to handle dependencies while executing the script because sometime tools execution speed does not match with the application speed or some web elements response time does not match with script actions.

So to handle synchronization, selenium webdriver provides two effective ways and those are-

  • Implicitly Wait
  • Explicitly Wait

An implicitly Wait tell to WebDriver to hold for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.

Here we go with sample code to achieve Implicitly Wait-

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;

namespace TestProject
{
[TestClass]
public class UnitTest1
{
IWebDriver driver;
[TestMethod]
public void TestMethod1()
{
driver = new ChromeDriver(@”D:\Download\VisualStudio_Projects”);
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMinutes(10));

driver.Navigate().GoToUrl(“http://www.bing.com&#8221;);
driver.Manage().Window.Maximize();
driver.FindElement(By.Id(“sb_form_q”)).SendKeys(“Mayank”);
driver.FindElement(By.Id(“sb_form_go”)).Click();
driver.Quit();

}
}
}

Explicit Wait is intelligent wait and for a particular Web Element. Using explicit wait we basically instruct the wait to x unit of time span before giving up and along with it we can include condition that if particular webelement appear with in x unit of time span then move to next line of code.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;

namespace TestProject
{
[TestClass]
public class UnitTest1
{
IWebDriver driver;
[TestMethod]
public void TestMethod1()
{
driver = new ChromeDriver(@”D:\BackUp\MyData\VisualStudio_Projects”);
driver.Navigate().GoToUrl(“http://www.bing.com&#8221;);
driver.Manage().Window.Maximize();
driver.FindElement(By.Id(“sb_form_q”)).SendKeys(“Mayank”);

WebDriverWait load = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
load.Until(ExpectedConditions.ElementExists(By.Id(“sb_form_go”)));

driver.FindElement(By.Id(“sb_form_go”)).Click();
driver.Quit();

}
}
}

Hope above code snippets will help to resolve any synchronization issue.

How to setup Selenium WebDriver with Visual Studio 2013?

Before setting up Selenium with Visual Studio, we should make sure that machine should have installed Visual Studio 2013 and NuGet.

So if above pre-requisites are in right place then start Visual Studio and create new project.

VS

Select Visual C# > Test > Unit Test Project. Provide project name, location and click on OK button.

VS1

Select your project and right click. Click on Manage NuGet Packages…option.

VS2

Make sure you are pointing to ‘Online‘. Search the term ‘Selenium‘ and install Selenium WebDriver and Selenium WebDriver Support Classes. Now close the ‘Manage NuGet Package‘ window.

VS3

We will use Chrome browser to execute our first selenium script, so for this download Chrome driver from here.

Download and extract the file.

Open UnitTest1.cs file and include following namespaces-

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

Now under TestMethod1() add following code-

IWebDriver driver = new ChromeDriver(@”D:\Download\VisualStudio_Projects”);
driver.Navigate().GoToUrl(“http://www.bing.com&#8221;);
driver.Manage().Window.Maximize();
driver.FindElement(By.Id(“sb_form_q”)).SendKeys(“Mayank”);
driver.FindElement(By.Id(“sb_form_go”)).Click();
driver.Quit();

VS4

Now run the method. It will open the Chrome browser with bing.com and will search the term.

Comment out if above steps are not working for you.