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.