Wednesday, October 15, 2014

*****ParallelExecution*****

package com.prac;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;



public class ParallelExe {
public static void main(String...strings ){

       Thread fireFoxThread=new Thread(new Runnable() {

public void run() {
// TODO Auto-generated method stub


WebDriver driver=new FirefoxDriver();
driver.get("http://www.google.com");
}
});

Thread chromeThread=new Thread(new Runnable() {

public void run() {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "D:\\Users\\browserdrivers\\chromedriver.exe");
WebDriver driver1 = new ChromeDriver();
driver1.get("http://www.amazon.com");

}
});

fireFoxThread.start();
chromeThread.start();

}
}

10.Selenium WebDriver – Architecture

I Try to Simplify as much as possible to understand how the architecture of Selenium formed.
Selenium WebDriver Divided into 3 major divisions
1. Language level Bindings
2. Selenium WebDriver API
3. Drivers
Language Level Bindings
We have a common API that has a common set of commands and we have various bindings for the different languages. So we can see there’s Java, Python, Ruby, etc..There’s also some other bindings and new bindings can be added very easily.
Selenium WebDriver API
Now these bindings communicate with Selenium WebDriver API and this API send the commands taken from language level bindings interpret it and sent it to Respective driver. In short term API contains set of common library which allow sending command to respective drivers.
Drivers
Internet Browser Specific Drivers such as IE, FF, Chrome etc..It works in headless mode which makes, text execution faster. It also contains mobile specific Drivers. The basic idea is each one of these drivers knows how to drive the browser that it corresponds to. For E.g. Chrome Driver knows how to handle the low level details of chrome driver and drive it to do things like clicking the target element, navigating the target page etc...
How it’s working:
You are writing your test in Java using common selenium API and that Java binding is sending commands across this common API. Now on the other end is listening a driver, it interpret those commands and executing them on the actual browser and return result backup using the API.  

9.Handling WebElement

Capture Screenshot of Web Page In Selenium WebDriver

Most of the time we think to Capture Screenshot in WebDriver when some kind of error or exception surfaces while practicing testing, to resolve the same WebDriver has provided us one interface TakesScreenshot for capturing the screenshot of web application and This interface provides one method names as getScreenshotAs() to capture screenshot in instance of driver. This getScreenshotAs() method takes argument of type OutputType.File or OutputType.BASE64 or Output.BYTES. So that it could return captured screenshot in File type, or Base 64 string type or in raw bytes.
So this would look like this
For File type
File scrnshot= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
For Base64 string above code would be like
((TakesScreenshot)driver).getScreenshotAs(OutputType.BASE64);
For BYTES
((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);
We have taken the screenshot with the help of getScreenshotsAs() method and  and now its time to copy this file somewhere in our file system or in our desktop. So for this purpose we further use copyFile() method of the FileUtils class from the org.apache.commons.io.FileUtils class.
Placing file in file system by using this line
FileUtils.copyFile(scrFile, new File(“e:\main_page.png”));
As I have told you that copyFile is a method of Class FileUtils and to call this method we need to write class.method() and in above code copyFile is taking argument from getScreenShotsAs() and new location where we want to save this captured Screenshot with name and with extension.
Now we would use write small running code that would open Google page and it would take a snap shot and that snap shot would be saved as google.png in my e: driver. One thing we need to remember whenever we work with File system or java.io then chances of exception is more so we would use try and catch in our code.
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class Chrome {
WebDriver driver;
@BeforeMethod
public void launchChrome()
{
System.setProperty("webdriver.chrome.driver", "E:\DD MISHRA\workspace\chromedriver_win_26.0.1383.0\chromedriver.exe");
driver = new FirefoxDriver();
driver.get("http://google.co.in");
}
@Test
public void googleScreenshot()
{
try {
File scrnsht =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrnsht, new
File("e:\google_page.png"));
} catch (Exception e) {
e.printStackTrace();
}
}
@AfterTest
public void kill()
{
driver.close();
}
}

Check if an element exists using WebDriver


IF you are a Selenium WebDriver  Automation tester than most probably you would have gone through this situation, In which you have faced one exception that speaks “Element not found”.
So why not, we get together and find first whether element is on page or not and than we perform the action on it.
Case 1:
Why not use implicit wait or explicit wait before the line of code that find the element for specific action. There might be possbility like element has not be loaded in to DOM and due to this exception is coming
Case 2: If Case 1: is not able to handle your problem than why not we use this line of code
Int i=driver.findElement(By.xapth(“your xpath”)).size();
if(i>0)
{
System.out.println(“Finally we got the element and now do the action on it”);
}

Case 3: If you are using ChromeDriver and trying to click on certain button than
try the same code on Firefox because Chrome Driver throw an exception that speaks like Element is not present at location with the co-ordinates
Case 4:
Why not we use isDisplayed() method first in If condition like this
if(dirver.findElement(By.id(“Id of Element”)).isDisplayed())
{ //now perform the action on this element
}

Handling JavaScript Alert in WebDriver


Handling JavaScript Alert is big question if you have just started learning WebDriver. Because we always get multiple pop-ups some time we get information about validity of input and some time these pop-up speaks about error, and also about response.
But as a tester we need to verify the alert message and for the same we need to handle the Alert pop up. So its time to celebrate because WebDriver have provided us with Alert class to deal with JavaScript Alert.
alertSince I have created this alert through a basic html file and  it has one button Ok. Butthere is another kind of alert known as Confirm Box Alert and it normally have two button
1-Ok button
2- Cancel button
Since both alert is handled in the same way so here I am taking the Confirm Box Alert here
Scenario : Suppose we have one button, and once we hit on the button a alert appears with two button Ok and Cancel
a) In first case if end user click on Ok button
@Test
public void testAlertOk()
{
//Now we would click on AlertButton
WebElement button = driver.findElement(By.id("AlerButton"));
button.click();
try {
//Now once we hit AlertButton we get the alert
Alert alert = driver.switchTo().alert();
//Text displayed on Alert using getText() method of Alert class
String AlertText = alert.getText();
//accept() method of Alert Class is used for ok button
alert.accept();
//Verify Alert displayed correct message to user
assertEquals("this is alert box",AlertText);
} catch (Exception e) {
e.printStackTrace();
}
}
b) In second case we want to click on Cancel button
So above code would remain same only thing that would change in above script is
alert.accept();
For clicking on Cancel we need to use dismiss() method of Alert Class
alert.dismiss();

8.Reporting in WebDriver

Email your failing Selenium WebDriver scripts’ Stack Trace to your Email Id

This is my new post and I am very excited because through this we would be able to find all Stack Trace of our failing WebDriver Scripts.This has been made possible through one of the Java Mail API.
1- Pre-requisite
First we need to download two jar files
1- javaee-api-5.0.3.jar
2- javamail1_4_7.zip
download both file from here
In this Java Mail API we use mainly two packages
1) javax.mail.internet.
2) javax.mail
In general we use three steps to send mails using Javamail API
1- Session Object creation that stores all the information like Host name, username and password
like this
Session session = Session.getDefaultInstance(props,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(“usermail_id”,”password”);
}
})
2- Setting Subject and Message body like this
message.setSubject(“Testing Subject”); //this line is used for setting Subject line
message.setText(“your test has failed <============================>”+ExceptionUtils.getStackTrace(e) );
3- Sending mail that could be done with this line of code
Transport.send(message);
2- Now I am pasting here my code of Mail sending class
package test_Scripts;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.commons.lang3.exception.ExceptionUtils;
public class SendMail{
public SendMail(String fromMail,String tomail, Exception e )
{
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("Email_Id","password");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromMail));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(tomail));
message.setSubject("Script failed");
message.setText("your test has failed for script name:Name of your scipt <============================>"+ ExceptionUtils.getStackTrace(e) );
Transport.send(message);
System.out.println("Done");
} catch (MessagingException ex) {
throw new RuntimeException(ex);
}
}
}

I have written one class SendMail with one constructor with three parameter. that I would call in my WebDriver script. and When My code would fail some where then It will send the Stack Trace.
3- My script of WebDriver

package test_Scripts;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class Except {
WebDriver d;
@BeforeMethod
public void launch()
{
System.setProperty("webdriver.chrome.driver", "E:\DD MISHRA\workspace\chromedriver_win_26.0.1383.0\chromedriver.exe");
d = new ChromeDriver();
}
@Test
public void test()
{
d.get("www.gmail.com");
try{
WebElement element= d.findElement(By.xpath("//div/span"));
element.sendKeys("dwarika");
}
catch(Exception e)
{
e.printStackTrace();
new SendMail("Sender_Mailid","Receiver_Mailid",e);
}
}
}

I have tried this code and find that we can use it in our selenium Scripting for sending mail for failing scripts. but I am hoping some more valuable advise from you people to use it in more optimized form..So if you have any other method then please let me know about the same.

Junit: Rerun failed Test cases instantly..!!


We guys encounter sometime in need to rerun our failed test cases instantly, But if we wanna retry our test case twice/thrice etc then it is not achievable with Junit. But if we are following TestNG we can do that very fast.
For Junit, How we can achieve is mentioned below:-
We can run this by defining a TestRule, This will give you the flexibility you need. A TestRule allows you to insert logic around the test, so you would implement the retry loop. For this you need to define a class in your framework :-
public class RetryTest {
public static class Retry implements TestRule {
private int retryCount;
public Retry(int retryCount) {
this.retryCount = retryCount;
}
public Statement apply(Statement base, Description description) {
return statement(base, description);
}
private Statement statement(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
Throwable caughtThrowable = null;
// implement retry logic here
for (int i = 0; i < retryCount; i++) {
try {
base.evaluate();
return;
} catch (Throwable t) {
caughtThrowable = t;
System.err.println(description.getDisplayName() + “: run ” + (i+1) + ” failed”);
}
}
System.err.println(description.getDisplayName() + “: giving up after ” + retryCount + ” failures”);
throw caughtThrowable;
}
};
}
}
}
================================================================
Now its very simple to rerun the test case with adding the rule before @Test:-
Say we want to run 3 retry for our test case
@Rule public Retry retry = new Retry(3);

7.Basics of Frameworks in WebDriver

Data Driven Testing in WebDriver Using jxl


Data Driven Testing through WebDriver using jxl
Prerequisite 

1- Download jxl jar file and add it in to path
2- Junit jar file
3- Selenium-server-standalone-2.x.jar
Add these three jar file in build path and to read more about adding jar file read my last post Configuring Selenium Webdriver in Eclipse with Testng plugin installation .
In general when we say Data Driven then only thing that should come in to mind is that input is going to be read from some xls file, xml,csv or some other table oriented file and might be output would also be written in xls,xml or csx file. All read data from various files are stored in variables and finally used by scripts to run the test cases.
Data Driven testing is mainly divided in two part
1- Reading data and storing in to variable
2- Using data stored in variable in to some generic script.
Reading Data and storing in to variable
Since Webdriver don’t have structure like other automation tools like QTP to have its own Data table to store data to run tests in Data Driven framework. So we normally two jar file(Binaries) JXL(Java Excel API) and Apache POI to make Data Driven test framework for  WebDriver.
I am using JXL binary in this example. so for reading data from xls file we need to follow these step
1- Opening Excel file , so to open excel file we would use these two line. I have created one excel file r.xls and now we would write code to reach to this file and to open this excel sheet.
import java.io.FileInputStream;
import jxl.Workbook;
FileInputStream fi = new FileInputStream(“C:\Users\kaushal\Desktop\r.xls”);
Workbook w = Workbook.getWorkbook(fi);
In above code
FileInputStream obtains input bytes from a file in a file system
2- Opening worksheet
import jxl.Sheet;
Sheet sh = w.getSheet(0); or w.getSheet(Sheetnumber)
Here 0 as argument states about firest sheet, if we want to read second sheet then we may use 1 in place of 0
3- Reading data
code used is 

String variable1 = s.getCell(column, row).getContents();
These are 3 steps that is used in reading data from excel sheet
In my example or code I am going to write code to test login to Gmail for various user and Username and Password is save in excel sheet and we will keep reading this data by using loop and we would store these data in two variable username and password
package com.testng;
import java.io.FileInputStream;
//import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Data{
Sheet s;
WebDriver driver;
@Before
public void setUp()
{
driver = new FirefoxDriver();
}
@Test
public void searchGoogle() throws Exception
{
FileInputStream fi = new FileInputStream("C:\Users\kaushal\Desktop\r.xls");
Workbook w = Workbook.getWorkbook(fi);
s = w.getSheet(0);
for(int row=1; row <=s.getRows();row++)
{
String username = s.getCell(0, row).getContents();
System.out.println("Username "+username);
driver.get("http://www.gmail.com");
driver.findElement(By.name("Email")).sendKeys(username);
String password= s.getCell(1, row).getContents();
System.out.println("Password "+password);
driver.findElement(By.name("Passwd")).sendKeys(password);
driver.findElement(By.name("signIn")).click();
}
}
@After
public void tearDown()
{
driver.close();
driver.quit();
}
}
excelsheet-sample1-300x62

Selenium Automation Frameworks


Based on the daily usage of framework, I hereby highlighting some major points regarding the Selenium automation framework.
-Any Automation framework build a layer over existing automation tools say-selenium.
-Framework Provides a library of functions that hides underlying complexity from users.
-Modular design makes it easy to extend & User friendly interface and reporting options.
-Uses Global parameters and variables to compensate for changes in application.
Below is the example for the same:-Image
Different Ways to Design A Framework:-
==>Test Script Modularity Framework
==>Data-Driven Automation Frameworks
==>Keyword-Driven Automation Framework
==>Hybrid Test Automation Framework
Test Script Modularity Framework:-
-Builds a abstraction layer in front of a component to hide the component from the rest of the application.
-Done by creating small, independent scripts.
-Each script represent modules, sections, and functions of the AUT.
-Small scripts can be combined to from larger tests
-Results in high degree of modularization and maintainability.
Data-Driven Automation Frameworks:-
-Test input and output values are read from data files (ODBC sources, CVS files, Excel files, DAO objects, ADO objects.
-These values loaded into corresponding variables in captured scripts.
-Test flow navigation coded into test script.
-Thus script is just a “driver,” or delivery mechanism, for the data.
-Data driven is the design of possible inputs what may given by the end user. This would cover maximum probabilities of an input data. It can be Spread sheet or sql. We have to connect and pass the values to the respective field or element.
-The data should be designed by the experienced person on the project. It may be a client or
even non technical person but should be more familiar with end user prospective. We have to map the file path properly.

Keyword-Driven Automation Framework:-
-Requires the development of data tables and keywords, independent of the test automation tool.
-Essentially represents a manual test case as a series of keywords or actions.
-In a keyword-driven test, the functionality of the application-under-test is documented in a table as well as in step-by-step instructions for each test.
Keyword driven framework is an action based test method used in planing and implementation of automation.
Sample Keyword Driven Table:
Module: Login
Sl.No
Element ID
Action
Data
Goal
1.
Txt_login
Type
5_Kings
2.
Txt_Password
Type
84#nu2|
3.
Txt_ConfirmPwd
Type
84#nu2|
4.
btn_Save
Click
Success Message
Hybrid Test Automation Framework:-
-Combination of all of the above techniques, pulling from their strengths and trying to mitigate their weaknesses
-Allows data driven scripts to take advantage of the powerful libraries and utilities in a keyword based approach
-The framework utilities can make the data driven scripts more compact and less prone to failure.
-The utilities can also facilitate conversion of existing scripts to keyword driven equivalents.
-On the other hand, the framework can use scripts to perform some tasks that might be too difficult to re-implement in a pure keyword driven approach.
Real Time Example of Automation framework in Selenium:-
Image
In above picture major Framework Components are :-
FRAMEWORK
-Main.rb
-Functionlibrary.rb
-Selenium.rb
ABSTRACT LAYER
-Object Repository
-Keywords
EXTERNAL DATA
-Data Sheets
-Global Variables
====================================================================
Descriptions are as follows:-
Main.rb:-
Driver Script That invokes other components of the framework.
Written in Ruby
Reads in test scripts (which are in excel format)
Main.rb invokes application under test.
Functionlibrary.rb:-
Invokes functions corresponding to keywords in test-script file from the function library.
Each Functions correspond to some actions that must be performed . E.g. Buttonclick, VerifyText.
Function Library can be customized to include additional functions not present in the repository
Selenium.rb:-
Selenium.rb holds all the built-in functions of Selenium tool.

Understanding and Writing Page Object in Selenium

Let’s first quickly understand the concept of page object before jumping in and writing it.
Page object to be concise, creating a relationship between each and every test method we execute, which can be done by returning page object in every method we call. This will ensure that our test execution is happening on the right page rather waiting for some object (UI) in a wrong page.
Well the above description sounds weird, since we are expecting a method to return object of page to perform another operation, but how to do that and how does it looks ?
Let’s consider we have a scenario like this, we have to login in our AUT (Application Under Test) and hit settings page and perform email configuration of Admin and check the logged in user got admin privilege.
Well, this can be done simply by writing methods for each and every operation mentioned and call them in sequence (Which is done more often) and perform operation, but the downside of this way of operation is
  • What if the page in sequence not loaded
  • What if the AUT landing in wrong page (rather landing in settings page, if it lands in logout page)
  • How to manage objects (UI object) of all pages
  • Duplication of code (functionalities)
In order to cope the above problems, page objects can be used.
Let’s see them as an example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  public class Login
    {
        public Login Login(string user)
        {
            //Perform some operation of login
            //Return Login Reference
            return new Login();
        }
    }
    public class Settings
    {
        public Settings settings(string SettingType)
        {
            //Perform some operation
            //Return settings
            return new Settings();
        }
    }
    public class EmailConfig
    {
        public EmailConfig EmailConfiguration(string configType)
        {
            //Return Email config
            return new EmailConfig();
        }
    }
    public class TestClass
    {
        public void testCreateEmailConfig()
        {
            Login log = new Login();
            Settings userSetting = log.Settings(“Admin”);
            EmailConfig config = userSetting.EmailConfiguration(“Admin”);
        }
    }
As you all could see from the above C# code snippet, we are creating separate class for each and every page and writing functionalities which those page provide in the same class itself and also each page will return the reference of the Type of the page, this makes us even more comfortable to make sure we are performing operations on the correct page.
Well, whatever we have seen so far is how we can create classes based on the functionalities within a page, now let’s see how we can write objects within a page. Objects for a page can be identified by either ID, CSS, XPath, LinkText etc, hence the object in the Page Object pattern can be written by referencing the namespaceusing OpenQA.Selenium.Support.PageObjects
and the objects can decorated using annotations in square brackets as shown below
1
2
3
4
5
6
7
8
9
10
11
//User Name
[FindsBy(How = How.ID, Using = "UserName")]
public IWebElement txtUserName { get; set; }
//Password
[FindsBy(How = How.ID, Using = "Password")]
public IWebElement txtPassword { get; set; }
//LoginWidget
[FindsBy(How = How.XPath, Using = ".//div[@widget-name='Login']//table]”)]
public IWebElement wdLogin { get; set; }
As shown in the above code, the UserName and Password textbox are identified using ID and Widget has been identified using Xpath. The FindsBy is an attribute found under usingOpenQA.Selenium.Support.PageObjects namespace. The attribute has named parameter type such as CustomFinderType, How, Priority and Using. The How is an enumeration type and has following

Once all the objects are written in the Page object class (Here Login class), we need to first initialize the Page object using InitElements method of PageFactory class. The code to initialize the object can be written like the one shown below
1
PageFactory.InitElements(driver, new Login); // Driver is the instance variable of FF driver
Here is how the Login class will looks like
1
2
3
4
5
6
7
8
9
10
11
12
public class Login
{
        public static void LoginAdmin()
        {
            LoginPageObject ObjectLogin = new LoginPageObject();
            //User Name
            ObjectLogin.txtUserName.SendKeys(“admin”);
            //Password
            ObjectLogin.txtPassword.SendKeys(“admin”);
        }
}
The intelli-sense will give us the entire object as shown

This will give us the understanding and overview of how to work with Page Object.


6.Wait in WebDriver

Implicit Wait in WebDriver

Implicit wait in WebDriver has solved the compile error of Element not found. Element not found kind of error mostly comes in to picture due to slow internet connection or some time due to responses time of Website or web-application and due to which expected element on the website/webpage takes more time to appear. This cause failure of test script written for that specific element on webpage.
Implicit wait in webdriver synchronize test. This implicit wait implementation in test ensure first that element is available in DOM(Data Object Model) or not if not then it wait for the element for a specific time to wait for appearance of element on Webpage.
Normally Implicit wait do the polling of DOM and every time when it does not find any element then it wait for that element for certain time and due to this execution of test become a slow process because implicit wait keep script waiting.Due to this people who are very sophisticated in writing selenium webdriver code advise not to use it in script and for good script implicit wait should be avoided.
Ok come to the point WebDriver API has one Interface named as Timeouts and this is used for implicit wait and since this is interface so have one function named as implicitlyWait(), this method takes the argument of time in Second, and this code is written like this
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
Here I have taken 5 second as wait, once script see any findElement() method then it goes for 5 second wait.
But this keeps script waiting for 5 second once it see a findElement() method so WebDriver API has introduced one explicit wait and in this WebDriverwait class play a very important role.
So in next post I would let you know about the Explicit wait and i would suggest to use explicit wait.

5.Assertions used WebDriver

How to use assertEquals() in WebDriver using driver.getText()


When we start making some  web application, We start with some UI and Every UI has menu, Check box, Button, Combo Box , Radio button, Text Field and other element of Web Application.
But most of the time we need to verify that Text or value associated with above mentioned elements of Web Application are correct or not and for this we commonly use two function
1- getText()
2- assertEquals().
getText() helps in retrieving the Text from an element by using WebElement class.This method returns the value of  inner text attribute of Element.

So why not take a look on this how it works
package com.testng.src.com.testng;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class Verify {
WebDriver driver;
@BeforeMethod
public void launch()
{
System.setProperty("webdriver.chrome.driver", "E:\DD MISHRA\workspace\chromedriver_win_26.0.1383.0\chromedriver.exe");
driver = new ChromeDriver();
}
@Test
public void verify()throws Exception
{
driver.get("http://google.co.in");
WebElement element = driver.findElement(By.xpath("//span[text()='Google Search']"));
String strng = element.getText();
System.out.println(strng);
Assert.assertEquals("Google Search", strng);
}
}
In this script
1- I have used xpath to find the Google Search button
2- By using findElement method we could find Google Search Button
3- Once we get the element, By using getText() method we could find the text on Button
4- By using assertEquals(), we verify that Google Search Text is available on Google Search Button. If text retrieved from getText() match with the String inserted in to asserEquals() method then test is passed otherwise it is  failed.
Result after execution of this code
Started ChromeDriver
port=22048
version=26.0.1383.0
log=E:DD MISHRAworkspaceDataDrivenWebdriverchromedriver.log
Google Search
PASSED: verify
===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================
There are other assert methods that could be used to verify the text in place of assertEquals()
assertTrue(strng.contains(“Search”));
assertTrue(strng.startsWith(“Google”));
assertTrue(strng.endsWith(“Search”));
If this text pattern match then test get passed other wise test get failed.


assertTrue(message,condition) in Selenium WebDriver and it’s implementation


assertTrue() is one of the most popular and frequently used assertion method while creating Selenium Scripts. Being an Automation tester/Engineer, the word assertTrue(Message, Condition) comes every now and then and for that matter of fact is almost used in every script whenever we intent to  “Check the presence of an element on a webpage”. Thus considering it’s importance, it has become an integral part of our testing routines/activities. In literal terms, the word can be interpreted as “to state to be true” and the same fundamental is brought into play while embedding assertions in the test scripts. Thus this post will give an essence of how can we use “assetTrue(condition)” in various context while creating test scripts. Before discussing “assertTrue(condition)” and its applicability, let’s have a look at its origination . assert1 Assertion tool class is a part of org.testng and extends java.lang.Object class. This class presents a wide variety of static methods with a specific parameter order. To name a few, there are methods like assertTrue(condition), assertFalse(condition), assertEquals(actualValue, ExpectedValue), assertNull(object) and many more. assertTrue(boolean condition) In a very simple language it asserts that a given condition is true.
assert2
If the given condition isn’t true, an AssertionError, with the given message is thrown.
public static void assertTrue(java.lang.String message, boolean condition)
Parameters: condition – the condition to evaluate message – the assertion error message Import statements: For using assertTrue() in our test scripts, we need to import it in the test script using the following syntax:
import static org.junit.Assert.assertTrue;
Conditions and Messages:  assertTrue(“Assertion Failed: Message”, boolean condition)
  • String equals() Method
 Description: This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object. Syntax:
assertTrue("Verification failed: Element1 and Element2 are not same.",Element1.equals(driver.findElement(By.id(Element2 )).getText()));
  • String equalsIgnoreCase() Method
 Description:  This method compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length, and corresponding characters in the two strings are equal ignoring case. Syntax:
assertTrue("Verification Failed: Element1 and Element2 are not same.",(driver.findElement(By.xpath(Element1 )).getText().equalsIgnoreCase(Element2)));
  • String substring() Method
 Description:  This method has two variants and returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string or up to endIndex – 1 if second argument is given. Syntax:
String name=”String Operation.AssertStatement”;
assertTrue(“Verification Failed: The name is not ”String” Operation”.”,driver.findElement(By.id("name")).getAttribute("value").equals(name.substring(0, name.lastIndexOf("."))));

Output: String Operation
  • String replaceAll() Method
Description: This method replaces each character of this string that matches the given regular expression with the given replacement. Syntax:
assertTrue(“Verification Failed: Message is not displayed correctly on the webpage.”,driver.findElement(By.id("message")).getText().replaceAll("[\t\n\r]", " ").equals("Testing Message is displayed correctly"));
Other than these, there are several other string operation methods available and can be effectively used in conjunction with assertTrue(). Some of the other commonly used methods are:
  • isSelected() Method
Description:  This method checks if the specified object is selected. The result is true if and only if the object is selected.  Syntax:
assertTrue("Verification Failed: The radio button of male status is not selected for the user", driver.findElement(By.id(“gender”)).isSelected());
  • getAttribute() Method
Description:  This method returns the value of the attribute whose key is specified .  Syntax:
assertTrue("Verification Failed: Data filled in Language field is not correct. Please check naming convention. ",driver.findElement(By.id("list_lg")).getAttribute("value").equals(language));
  • Using Select
Description:  Helps to select and de-select options in the dropdowns.
assert3
Syntax:
assertTrue("Verification Failed: Data filled in font field is not correct. Please check naming convention. ",driver.findElement(By.id("list_lg")).getAttribute("value").equals(“Georgia, Times New Roman, Times, serif”));
  • isDisplayed() and isEnabled() in conjunction 
Syntax:
assertTrue(“Verification Failed: Either element1 is not being displayed or element2 is not enabled.”,driver.findElement(By.id("element1")).isDisplayed()
                    && driver.findElement(By.id("element42")).isEnabled());

Furthermore, there can be numerous other similar combinations.

Introduction to driver.getPageSource()

Might be most of you would have used it in your day to day scripting or if not then don’t worry I am trying to make it chew-able that would finally get digested well.
People who has started learning Selenium would be familiar with Selenium RC and hoping would be familiar with Selenium IDE. In RC and IDE we have option to validate or verify any text on the page by using methods like
selenium.isTextPresent();
or in IDE we normally select the text and by right clicking we normally add assert or verify method for specific text. But Selenium 2(WebDriver) don’t have any direct method to find the text and also don’t have any assertion associated with it. But still we have many thing to work with.
there is one method in Selenium2 getPageSource(), it fetch all the source of a specific webpage and that can be user to verify the text on the page
Suppose there is one webpage where there is one string “Selenium is Browser automation tool”.
Here we can find it two way
1st Method
assertEquals("Selenium is Browser automation tool", driver.findElement(By.xpath("Xpath of the element")).getText()).
By using this we would be able to find that text is available or not if it is not then script will fail here otherwise it will get passed
Method 2:
This is most popular one to fulfill our requirement. but the result that come is in Boolean
Boolean b =  driver.getPageSource().contains("Selenium is Browser automation tool").
it result will appear in true or false and this is further used to implement some condition while writing scripts.
Main use of this Method
1- To find the text on the page
2- to find the pop up by some text on it.

4.Parallel Execution of Script in various browser*****

How to execute Selenium WebDriver test cases parallel in multiple Browser using Testng parameter Annotation


I am supposing that you are familiar how to add jar files to your project and How to add any  class, folder and xml.
Most of the time we find it hard to do compatibility testing of certain web-page on various Browsers and it takes a big chunk of time for its execution on various set of Browser and also on various instance of Browser.
Testng has provided us an option through its Parameter feature, through which we could run same test script written in WebDriver  parallel to all our installed Browser on our system.
Scripts and Steps to execute Script 
1- Go to your Eclipse Project –> Right Click on Project –> Click On New–> others–> Pop up would appear–> Click on XML –> Select XML File –> Click on Next –> New XML File pop up would appear–> Enter the name of XML and click on Finish
2- Your XML file would appear like this
<!–?xml version=”1.0″ encoding=”UTF-8″?>–>
Replace this with this code
<suite name=”Suite1″ verbose=”1″ parallel=”tests”>
<test name=”Generic test” >
<parameter name=”browser” value=”FF”></parameter>
<classes>
<class name=”com.testng.Test” />
</classes>
</test>
<test name=”Generic test_ie” >
<parameter name=”browser” value=”IE”></parameter>
<classes>
<class name=”com.testng.Test” />
</classes>
</test>
<!–suite>–>
Download xml file from here
Now understand the tags of XML that I have marked Bold in XML file
Parallel:  this is being used to run tests parallely in different browser
suite name: This is the name of your test suit
test name : kind of test cases (you may give name like this Regression, Sanity,Smoke, or any thing that make you to make better test execution ) like i have given name to this test case as Generic test
Classes: name of class that you want to add in this test execution
Most important one is
<parameter name=”browser” value=”FF”></parameter> Here I have browser as parameter name(u can have any name to it) and Value here I have given FF for Firefox,IE for Internet Explorer, and Chrome for Chrome Browser.
3- Now its time to understand how we have to use parameter name in Java program. Since parameter is defined for Browsers. Since we are trying to use Testng framework we would  write two function first one to launch Browser and Second one to close Browser
Create new java class in your Java Project
Steps to create new java class:: right click on project ||New|| Click on Class||Enter the name of class and Hit on finish.
Name of my java class is Browser.java

package com.testng;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Parameters;
//import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
public class Browser {
WebDriver driver;
@BeforeMethod   /* The annotated method will be run before all tests in this suite have run */
//browser is the name of parameter that we have used in xml
@Parameters(“browser”)  /* this annotation is used to insert parameter in test*/
public void openBroswer(String browser){
/*Comparing the value of parameter name if this is FF then It would launch Firefox and script that would run is as follows */
if(browser.equalsIgnoreCase(“FF”))
{
System.out.println(“Firefox driver would be used”);
driver = new FirefoxDriver();
}
else
{
System.out.println(“Ie webdriver would be used”);
driver = new InternetExplorerDriver();
}
}
@AfterMethod /* this annotation would run once test script execution would complete*/
public void closeBrowser()
{try{
driver.wait(15000);
}
catch(Exception e){}
driver.close();
driver.quit();
}
}
4- Since we have created Browser class in which we have used the parameter defined in XML, Now we should create one more class that is our Test class, This class would inherit Browser class for launching Browser before executing scripts under @Test annotation and for Closing Browser once execution of scipt under @Test annotation get completed.
here I have given the name of this class is Test

package com.testng;

import org.openqa.selenium.By;
import org.testng.Reporter;
import org.testng.annotations.Test;
@Test
public class Test extends Browser{
public void test(){
/* in this test we are searching selenium in Google and clicking on first link in Google Result*/
driver.get(“http://www.google.com”);
driver.findElement(By.id(“gbqfq”)).sendKeys(“selenium”);
//driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver.findElement(By.xpath(“//ol[@id='rso']/li[1]//h3/a”)).click();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
5- Now its time to execute Test-Case
Steps:
Right Click on Test.java file and –> Run As –> Run Confinguration –> In pop up Go Testng –> Right Click on Testng and Click on New –> Give name to your Run Configuration, Browser Class and select your Xml just by Browsing in front of Suit –> hit on Finish and this would run your test
TestNg-Config

3.Browser things in WebDriver

Accepting Untrusted SSL certificate in WebDriver for Chrome and Firefox Browser


firefox-certificate-errorSome time we get these SSL errors or notification when we try to execute our scripts, but WebDriver has provided us to give capabilities to the Chrome Driver/Firefox to handle these things
Here I am posting the code that would help you in resolving the SSL error mainly in Chrome Browser
DesiredCapabilities capability = DesiredCapabilities.chrome();
capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
driver = new ChromeDriver(capability);

Above script will help you in accepting all the SSL certificate and by doing so you would not get any SSL error while executing your code.
In Firefox you need to apply this code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
public class acceptSSLCerti {
 public static void main(String[] args) {
 //Class ProfilesIni details
 ProfilesIni allProfiles = new ProfilesIni();
 // Use FirefoxProfile Constructor
 FirefoxProfile myProfile = allProfiles.getProfile("CertificateIssue"); myProfile.setAcceptUntrustedCertificates(true); myProfile.setAssumeUntrustedCertificateIssuer(false);
 WebDriver Driver = new FirefoxDriver(myProfile); Driver.get("http://abodeqa.wordpress.com");
}
}
Hope after using these code you would not face SSL error in your script execution.

Launch Chrome Browser Using WebDriver


Launching Chrome Browser using WebDriver
In WebDriver, We launch FireFox and Internet Explorer by using
WebDriver driver = new FirefoxDriver(); //this line would launch Firefox
WebDriver driver = new InternetExplorerDriver(); //this line would launch IE browser

But when we write below line like FireFox and IE
WebDriver driver = new ChromeDriver();
Then It throws Error and Here I am pasting Error Trace shown in Eclipse
java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see http://code.google.com/p/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://code.google.com/p/chromedriver/downloads/list
at com.google.common.base.Preconditions.checkState(Preconditions.java:176)
IT seems really tedious na, But there is one way to resolve this Error and this could be done by using this
1- Download zip file of chromedriver for Windows from here
 2- Unzip downloaded Chromedriver for Windows and find the absolute path of chromedriver.exe
3- Now set Property of System by using this line
System.setProperty(“webdriver.chorme.driver”,”E:\\DD MISHRA\\workspace\\chromedriver_win_26.0.1383.0\\chromedriver.exe”);
and after this line write your traditional line to launch the browser like this
WebDriver driver =new ChromeDriver();

So why not we write one script that help us to see the launching of Chrome

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Chrome {
WebDriver driver;
@Before
public void launchChrome()
{
System.setProperty("webdriver.chrome.driver", "E:\\DD MISHRA\\workspace\\chromedriver_win_26.0.1383.0\\chromedriver.exe");
driver = new ChromeDriver();
}
@Test
public void testChrome()
{
driver.get("http://www.google.co.in");
driver.findElement(By.id("gbqfq")).sendKeys("Selenium");
}
@After
public void kill()
{
driver.close();
driver.quit();
}
}


Unexpected error launching Internet Explorer. Protected Mode must be set to the same value


When we try to launch IE using WebDriver on a very first time on a fresh computer by using this code
WebDriver driver = new InternetExplorerDriver();
driver.get("http://abodeqa.wordpress.com");
Then we filled with amazement when we find this exception
org.openqa.selenium.WebDriverException: Unexpected error launching Internet Explorer. Protected Mode must be set to the same value (enabled or disabled) for all zones. (WARNING: The server did not provide any stacktrace information)
System info: os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.6.0_25'
Driver info: driver.version: InternetExplorerDriver
 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
 at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
 at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
 at java.lang.reflect.Constructor.newInstance(Unknown Source)
 at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:131)
 at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:105)
 at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:409)
 at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:103)
 at org.openqa.selenium.ie.InternetExplorerDriver.setup(InternetExplorerDriver.java:104)
 at org.openqa.selenium.ie.InternetExplorerDriver.<init>(InternetExplorerDriver.java:61)
On seeing the exception message we normally come to know the root of this exception and after few minute of search on Google we are loaded with two option.
Option 1:- by using capabilities
DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
caps.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
WebDriver driver = new InternetExplorerDriver(caps);
Why We use Capability:
When the rewritten IE driver was first introduced, it was decided that it would enforce its required Protected Mode settings, and throw an exception if they were not properly set. Protected Mode settings, like almost all other settings of IE, are stored in the Windows registry, and are checked when the browser is instantiated.
But the Indian Idiotic IT department does not give proper rights to change the system setting..(This gives them immense pleasure like they have hired donkey and would keep them busy in finding the bypass of this hack of their non-sense credential hunt..)(:D) So to cope with such problems we need this capability.Because this bypass the registry check for initializing IE browser.
But this also cause some unwanted thing like
  1. Hangs
  2. Element location not working
  3. clicks not being propagated
Option 2: If you have rights to change the small setting in your system than try this
Go to Internet Option in IE –> Security–>Check or Unchecked “Enable Protected Mode.” protected-mode-setting

Note that you don’t have to change the slider for security level, and you don’t have to disable Protected Mode. I routinely run with Protected Mode turned on for all zones, as I think it provides a more secure browsing experience.

Adding add-on in Firefox and Chrome using WebDriver

Title sounds interesting. But think once again if you are told to start testing on instance of Firefox or Chrome installed with certain add-on then might be this article would favorably help you in time of need.
Let me do the operation on Firefox..so are you ready !!!
Steps:
1-  For this we need to create one profile
FirefoxProfile firefoxprofile = new FirefoxProfile();

2- Now go to add-on’s binary download page and download the add-on with .xpi extension and save it in Default Download location.Suppose taking path of .xpi file is c:/add-on
oh still you are thinking what we need to do then
3- Read the file location by using File class that we normally use for creation of files and directories, file searching, file deletion etc.
File addonpath = new File("path of .xpi file");
4-  Now time has came to call the addExtension() of FirefoxProfile class.This method will install add-on in new profile created with new Instance of Firefox.
firefoxprofile.addExtension(addonpath);
Now pass this profile in to new instance of FirefoxDriver
As a whole this code will look like this in Eclipse to install add-on in Firefox using WebDriver

FirefoxProfile firefoxprofile = new FirefoxProfile();
File addonpath = new File("path of .xpi file");
firefoxprofile.addExtension(addonpath);
WebDriver driver = new WebDriver(firefoxprofile)

So now task is complete for Firefox but still we need to do the same for Chrome.
But don’t think that same step we are going to follow again. Because in Chrome we need to create instance of ChromeOption class . This class has many methods like addExtension()- This method is used to install add-on in new instance of Chrome, setBinary()- This method is used to Sets the path to the Chrome executable, setArguments()- Adds additional command line arguments to be used when starting Chrome.
Steps for Chrome:
1-
Download the add-on in default location and read it using File Class again like above
File addonpath = new File("path of .crx file");
2- Now create instance of ChromeOptions
ChromeOptions chrome = new ChromeOptions();
chrome.addExtensions(addonpath);
WebDriver driver = new ChromeDriver(options);


2.Selenium WebDriver Configuration and other supported installation

Configuring Android WebDriver in Eclipse


Configuring  AndroidDriver in Eclipse
1-      Download  Android server apk from this URL https://code.google.com/p/selenium/downloads/listandroid-apk
2-   Download android SDK from this location
http://developer.android.com/sdk/index.htmlandroid-sdk

3-      Unzip it in some location like C:/SDK
4-      You will see three folder ther

  •  Eclipse
  • SDK Manager.exe
  • sdksdk
Like this

Here you can use the eclise from here and so no need to configure here in eclipse it is already there in eclipse

Now you need to Create Android Virtual Device
Go to  Window >>AVD Manager>>
or
5-      Avd can also be created by command line
But for that you need to reach to the directory path of <sdk> tools
so open you Command prompt write this line (as my tools is present at this location)
cd C:androidadt-bundle-windows-x86sdktools
now write this line

android create avd -n my_android -t 14 -c 512M

Here  -n stands for specification of the avd name
-t  is used here for It specifies the platform target. Use the android list targets command to get the list of platforms available with the SDK.
-c  targets to SD card in mobile
6-      Lauching emulator
  1. a.       By using command line (navigate to platform tool location)emulator -avd my_android &    launching-emulator
  2. b.      By using manually
    Window >>Android Virtual Device Manager >> select already created AVD and click on start
7-      Finding  device id (I am assuming that we are in platform-tools directory on CMD)
write this command in CMD
adb devices    By default it will give id like this emulator-5554
8-      Now  copy your androidDriver apk and place it in platform-tools folder
9-      Now installing the apk in  newly created AVD(assuming that we are in platform-tools directory in cmd)
adb -s emulator-5554 -e install -r  android-server-2.21.0.apk
10-   Starting  Android-server (assuming we are in platform-tools directory on CMD)
adb -s emulator-5554 shell am start -a android.intent.action.MAIN -n org.openqa.selenium.android.app/.MainActivity -e debug true
11-   Setting up the port forwarding in order to forward traffic or script injection from local machine to emulator
adb -s emulator-5554 forward tcp:8080 tcp:808
But if you want to install plug-in of Android WebDriver in to your eclipse 
Steps:
1- Go to Help>> Install new software >> Add
https://dl-ssl.google.com/android/eclipse/
and Follow the instruction and finally you would be able to configure the Android WebDriver   plugin in Eclipse.

Downloading and Configuring Selenium Webdriver in Eclipse with Testng plugin installation


Downloading and Configuring Selenium WebDriver in Eclipse

Steps:
  1. To Download Selenium WebDriver jar file  Go to http://seleniumhq.org/download/
  2. Now Click on 2.30 under the label Selenium Server (formerly the Selenium RC Server)selenium-standalone-jar
  3. Now Open Eclipse and Create one Java project
  • Right Click on Left hand side in Eclipse under Package Explorer like in Imagenew-eclipse-java-project
  • Select NEW|JAVA PROJECT as marked in Imagenew-java-project-in-eclipse
  • Enter the name of Project Here I have mentioned New Project and Click on Finish button project-created-in-eclipse
  • Go to Project Explorer Label and See new project has been created as in Image
  • Now Select you project and Select  NEW|Folder as in Imagecreating-new-foldernew-folder-created
  • Another Window Open Enter the name of Folder and Click on Finish as in Image java-client-location
  • Now go to Location where Java Client  has been downloaded  and Copy the Selenium Server
  • Copy Selenium Server Standalone jar in Lib folder created under NewProjectadding-jar-file-to-path
  • Now add this standalone file in to path   by doing Right Click on Selenium Server Standalone 2.24.jar – Go to Build path|Add to Build Path as in image
  • Now you would see a new Label named as Reference Library as in Imageadded-jar-in-build-path
  • By adding Selenium Server Standalone 2.24.jar we have configured Webdriver in Eclipse

Configuring TestNG in Eclipseconfiguring-testng

  1. In Eclipse go to Help|Install New Software 
  2. Enter  http://beust.com/eclipse in the field as displayed in the image below and Click on Add Button on the right side of this text field, A pop up will appear, Enter the name TestNG and click on ok button and wait for few second. After this wait you See TestNg and Select check box of  TestNg  and then click on Next and Follow the Instruction and finally click on Finish and Refresh Eclipse.beust
  3. Note : In between installation one pop alert will appear before you that will ask your permission to install testng since it is not trusted, In this click on Ok button..wait for installation of Testng
  4. Question arises how we know that TestNg has been configured in Eclipse
    Stepstestng-config-test
  • Go to Window | Show View | Other as in Image testngconfig
  • Now Select Java|TestNG|GO testng
  • Finally to see whether Eclipse is configured or not do a final touch Right Click on you Peoject|Run As|TestNg Test as in Image
Finally we are done with configuration of Selenium WebDriver and TestNG

Installing Maven Plugin in Eclipse

Installing Maven plugin in Eclipse
1-     Download Eclipse
http://www.eclipse.org/downloads/
2-     Unzip and Click on Eclipse.exe
3-     Now in Eclipse  Click  Help-> Install New Software
4-     Type the following URL in field Work withhttp://download.eclipse.org/technology/m2e/releases

5-     Click Add
6-     Give any name for the repository
7-     Click OK
8-     Select the checkbox Maven Integration for Eclipse
9-     Click Next etc. to move forward and choose to restart Eclipse when prompted

Creating First Maven Project in Eclipse

Here  i am posting new post to create new maven project that i have learned from various sites and blot  and i got this very useful and want to share this with people who are also like me, and has started learning Selenium from scratches.
1- In Eclipse File ->New-> Other-> Maven-> Maven Project


2- Now Click Next, Next and Next
3- Type in field Group Id: com.Projectgroup.selenium Example com.Dwarika.selenium
4-Type in field Artifact Id: projectname Example : Webdriver
5-Click: Finish
After this you will see the hierarchical structure like this in Eclipse  where you would be able to see pom.xml in which you put all dependencies for your Maven Project

In Above snap number 4 you would be able to see the dependencies for junit and Slenenium
Dependencies that we need to change as per the use
1) We will change junit version to 4.7 or recent one is 4.9
in my case i have taken version for junit is 4.7
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.9</version>
  <scope>test</scope>
</dependency>
To add dependecy for Selenium we need to put this like given below
  org.seleniumhq.selenium
  selenium-java
  2.6.0

-- Here Eclipse will detect changes in pom.xml automatically and will download or update all dependencies as per the requirement
-- After the build is finished, there should be selenium*.jar files under Maven Depe