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.

 

Advertisements