Wednesday, October 15, 2014

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.

No comments:

Post a Comment