Wednesday, 30 September 2015

Commenly used Assert comparisons

package Flowell_testing;
import org.junit.Ignore;
import org.junit.Test;
import org.testng.Assert;

public class AssertTest {
 
    @Ignore
    @Test
    public void assertBooleanCompare() throws Exception {
        boolean actual = true;
        boolean expected = false;
        Assert.assertEquals(actual, expected);
    }
  
    @Ignore
    @Test
    public void assertStringCompare(){
        String actual = "yes";
        String expected = "no";
        Assert.assertEquals(actual, expected);
    }
   
    @Ignore
    @Test
    public void assertIntCompare(){
        int actual = 10;
        int expected = 10;
        Assert.assertEquals(actual, expected);
    }
   
    @Ignore
    @Test
    public void AssertTrue(){
        boolean status = true;
        Assert.assertTrue(status);
    }
   
    @Test
    public void AssertFalse(){
        boolean status = false;
        Assert.assertFalse(status);
    }
   
}

Monday, 28 September 2015

MOUSE HOVER ACTIONS IN SELENIUM WEBDRIVER

In order to perform a ‘mouse hover’ action, we need to chain all of the actions that we want to achieve in one go. So move to the element that which has sub elements and click on the child item. It should the same way what we do normally to click on a sub menu item.

With the actions object you should first move the menu title, and then move to the sub menu item and click it.

Below is the sample code to perform Mouse hover action

Example 1:

Actions actions = new Actions(driver);
WebElement mainMenu = driver.findElement(By.linkText(“menulink”));
actions.moveToElement(mainMenu);

WebElement subMenu = driver.findElement(By.cssSelector(“subLinklocator”));
actions.moveToElement(subMenu);
actions.click().build().perform();

Example 2:


Actions action = new Actions(webdriver);
WebElement mainMenu = webdriver.findElement(By.linkText(“MainMenu”));
action.moveToElement(mainMenu).moveToElement(webdriver.findElement(By.xpath(“submenuxpath”))).click().build().perform();
There are cases where you may just want to mouse hover on particular element and check if the button state/color is changing after mouse hover.

Below is the example to perform mouse hover

WebElement searchBtn = driver.findElement(By.id(“searchbtn”));

Actions action = new Actions(driver);
action.moveToElement(searchBtn).perform();

BROWSER COMPATIBILITY TESTING USING SELENIUM AND TESTNG

Cross Browser Testing : Is  to check that your web application works as expected in different browsers.If we are using Selenium WebDriver, we can automate test cases using Internet Explorer, FireFox, Chrome, Safari browsers.To execute test cases with different browsers in the same machine at same time we can integrate TestNG with Selenium WebDriver.


Lets create a class Testng_BC.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.Reporter;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class Testng_BC
{
public WebDriver fd;
@Test
@Parameters({“browser”})
public void browserTest(String str) throws Exception
{
if(str.matches(“firefox”))
{

fd=new FirefoxDriver();
fd.get("http://qtpseleniumsolutions.blogspot.in/");
fd.close();

}
if(str.matches(“ie”))
{

//Following code is to set the ie driver with webdriver property.You need IE Driver //server. download from here.
System.setProperty(“webdriver.ie.driver”,”F:\\Selenium_project\\IEDriverServer.exe”);
fd=new InternetExplorerDriver();
fd.get(
"http://qtpseleniumsolutions.blogspot.in/");
fd.close();

}
else {
Reporter.log(“test failed”);
}

}
}

Now create testng.xml file and paste the below code

<suite name=”Suite“>

<test name=”FirefoxTest“>
  <parameter name=”browser“ value=”firefox“ />
<classes>
  <class name=”Testng_BC“ />
  </classes>
  </test>
<test name=”IETest“>
  <parameter name=”browser“ value=”ie“ />
<classes>
  <class name=”Testng_BC“ />
  </classes>
  </test>
  </suite>
To execute a testcase in IE browser we have to use IE Driver server.And you have change few settings.
1.Open IE
2.Go to Tools -> Internet Options -> Security
3.Set all zones to the same protected mode, enabled or disabled should not matter.
Finally, set Zoom level to 100% by right clicking on the gear located at the top right corner and enabling the status-bar. Default zoom level is now displayed at the lower right.
Why are we passing parameters ??
To run the Testng_BC class in multiple browsers, we have to pass the parameters from xml.From parameters in testing.xml we can pass browser name and in test case we can create WebDriver reference accordingly.
Now run the testng.xml file, it should execute ‘browserTest’ in Firefox and  IE Browsers.If you refresh the project and look into test-output folder, a html report (index.html) has been generated.

MOST COMMON EXCEPTIONS WHICH WE NOTICE IN SELENIUM WEBDRIVER.

NoSuchElement : An element could not be located on the page using the given search parameters.


NoSuchFrame : A request to switch to a frame could not be satisfied because the frame could not be found.

StaleElementReference : An element command failed because the referenced element is no longer attached to the DOM.

Firefox Not Connected : Firefox browser upgraded toop new version.

ElementIsNotSelectable : An attempt was made to select an element that cannot be selected.

UnknownCommand : The requested resource could not be found, or a request was received using an HTTP method that is not supported by the mapped resource.

ElementNotVisible : An element command could not be completed because the element is not visible on the page.

InvalidElementState : An element command could not be completed because the element is in an invalid state (e.g. attempting to click a disabled element).

UnknownError : An unknown server-side error occurred while processing the command.

JavaScriptError : An error occurred while executing JavaScript code.

XPathLookupError : An error occurred while searching for an element by XPath.

Timeout : An operation did not complete before its timeout expired.

NoSuchWindow : A request to switch to a different window could not be satisfied because the window could not be found.

InvalidCookieDomain : An illegal attempt was made to set a cookie under a different domain than the current page.

UnableToSetCookie : A request to set a cookie’s value could not be satisfied.

UnexpectedAlertOpen : A modal dialog was open, blocking this operation

NoAlertOpenError : An attempt was made to operate on a modal dialog when one was not open.

ScriptTimeout : A script did not complete before its timeout expired.

InvalidElementCoordinates : The coordinates provided to an interactions operation are invalid.

IMENotAvailable : IME was not available.
IMEEngineActivationFailed : An IME engine could not be started.

InvalidSelector : Argument was an invalid selector (e.g. XPath/CSS).

DATABASE TESTING USING SELENIUM

Generally We don’t have to Test entire database of our application.To my knowledge, We use Selenium to test the Database whether data given in the front end(UI) is as same as the data present in the Database(Back End).

Note: We don’t do negative testing in database.

Here i am using MySql to test the database.
You need to Download Java.sql jar and configure database in your system. I’ll explain database configuration in Upcoming posts.


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;

public class testng_8
{
public WebDriver fd;
@Test
public void method_sql() throws Exception
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection cn=DriverManager.getConnection(“jdbc:mysql:wombat”, “myLogin”, “myPassword”);
Statement st=cn.createStatement();
ResultSet rs= st.executeQuery(“select * from emp”);
try {
while (rs.next())
{
System.out.println(rs.getString(0));

}
cn.close();

}
catch (Exception e)
{
System.out.println(“invalid”);
}

}
}

GENERATE CUSTOMIZED EXCELREPORTS USING TESTNG IN SELENIUM

Download the Jar from here ExcelReportGenerator. Add this Jar into your project BuildPath.

Step1 : Create a Package ‘ExcelResults’ under your Project.

step2 :Create  the testcases which you’d like to automate using TestNg. (by using @Test,BeforeTest,…….) as Shown.

import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;

public class Test_98 {
@Test(priority = 1)
public void VerfyingTestCaseID_001() {
System.out.println(“test”);
System.out.println(“this”);
}

@Test(priority = 2)
public void VerfyingTestCaseID_002() {
System.out.println(“test”);
System.out.println(“this”);
}

@Test(priority = 3)
public void VerfyingTestCaseID_003() {
System.out.println(“test”);
System.out.println(“this”);
}

@Test(priority = 4)
public void VerfyingTestCaseID_004() {
System.out.println(“test”);
System.out.println(“this”);
}

@Test(priority = 5)
public void VerfyingTestCaseID_005() {
System.out.println(“test”);
System.out.println(“this”);
Assert.assertEquals(“validText”, “InvalidText”);
}

@Test(priority = 6)
public void VerfyingTestCaseID_006() {
System.out.println(“test”);
System.out.println(“this”);
}

@Test(priority = 7)
public void VerfyingTestCaseID_007() {
System.out.println(“test”);
System.out.println(“this”);
Assert.assertEquals(“validText”, “InvalidText”);

}

@Test(priority = 8)
public void VerfyingTestCaseID_008() {
System.out.println(“test”);
System.out.println(“this”);
}

@Test(priority = 9)
public void VerfyingTestCaseID_009() {
System.out.println(“test”);
System.out.println(“this”);
}

@Test(priority = 10)
public void VerfyingTestCaseID_010() {
System.out.println(“test”);
System.out.println(“this”);
}

@Test(priority = 11)
public void VerfyingTestCaseID_011() {
System.out.println(“test”);
System.out.println(“this”);
Assert.assertTrue(false);
}

@Test(priority = 12)
public void VerfyingTestCaseID_012() {
System.out.println(“test”);
System.out.println(“this”);
Assert.assertTrue(false);

}

@Test(priority = 13)
public void VerfyingTestCaseID_013() {
System.out.println(“test”);
System.out.println(“this”);
}

@Test(priority = 14)
public void VerfyingTestCaseID_014() {
System.out.println(“test”);
System.out.println(“this”);
}
}

Step3 : Create a testng.xml file under your Project as Shown.

<suite name=”Build 2.0.1?>

<test name=”TestReport”>
<classes>
<class name=”Test_98? />
</classes>
</test>
</suite>

Now Run the testng.xml file.

Step 4 : Now Create a Class ‘ExcelGenerate’  and paste the following code.

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;
public class ExcelGenerate {

public static void main(String[]args) throws ParserConfigurationException, IOException, SAXException
{
ExcelReportGenerator exe= new ExcelReportGenerator();
exe.GenerateExcelReport(“YourTestName.xlsx”);

System.out.println(“Reports Generated in ExcelResults Package.Please refresh the packages”);

}
}

Step5 :Refresh the Package ‘ExcelResults’

MOST COMMONLY USED METHODS IN YOUR SELENIUM FRAMEWORK.

package utility;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
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.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.internal.Coordinates;
import org.openqa.selenium.internal.Locatable;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Utils {
public static WebDriver driver = null;
public static String browserName = null;

public static WebDriver openFirefoxBrowser() throws Exception {
try {
driver = new FirefoxDriver();
Log.info(“New driver instantiated”);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Log.info(“Implicit wait applied on the driver for 10 seconds”);
driver.get(Constant.URL);
Log.info(“Web application launched successfully”);

} catch (Exception e) {
Log.error(“Class Utils | Method OpenBrowser | Exception desc : ”
+ e.getMessage());
}
return driver;
}

public static String getBrowserName() {
browserName = System.getProperty(“browser”);

if (browserName == null)
browserName = “ie”;
return browserName;
}

public static WebDriver createWebDriver(String browser) {
System.out.println(“Browser: ” + browser);

switch (browser.toLowerCase()) {
case “ff”:
case “firefox”:
driver = new FirefoxDriver();
break;

case “ch”:
case “chrome”:
System.setProperty(“webdriver.chrome.driver”,
“E://chromedriver.exe”);
driver = new ChromeDriver();
break;

case “ie”:
case “internetexplorer”:
driver = new InternetExplorerDriver();
break;

default:
System.out.println(“Invalid browser name ” + browser);
System.exit(0);
break;
}// switch

driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.manage().timeouts().setScriptTimeout(45, TimeUnit.SECONDS);

return driver;
}

public static void switchToNewWindow() {
Set s = driver.getWindowHandles();
Iterator itr = s.iterator();
String w1 = (String) itr.next();
String w2 = (String) itr.next();
driver.switchTo().window(w2);
}

public static void switchToOldWindow() {
Set s = driver.getWindowHandles();
Iterator itr = s.iterator();
String w1 = (String) itr.next();
String w2 = (String) itr.next();
driver.switchTo().window(w1);
}

public static void switchToParentWindow() {
driver.switchTo().defaultContent();
}

public static WebDriver openIEBrowser() throws Exception {
try {
System.setProperty(“webdriver.ie.driver”, “D:\\IEDriverServer.exe”);
driver = new InternetExplorerDriver();
Log.info(“New driver instantiated”);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Log.info(“Implicit wait applied on the driver for 10 seconds”);
driver.get(Constant.URL);
driver.navigate()
.to(“javascript:document.getElementById(‘overridelink’).click()”);
Log.info(“Web application launched successfully”);

} catch (Exception e) {
Log.error(“Class Utils | Method OpenBrowser | Exception desc : ”
+ e.getMessage());
}
return driver;
}

/*
* public static String getMethodName() {
*
* String methodName = Thread.currentThread().getStackTrace()[1]
* .getMethodName(); System.out.println(methodName);
*
* return methodName; }
*/

public static void waitForElement(WebElement element) {

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(element));
}

public static void waitTillElementFound(WebElement ElementTobeFound,
int seconds) {
WebDriverWait wait = new WebDriverWait(driver, seconds);
wait.until(ExpectedConditions.visibilityOf(ElementTobeFound));
}

public static void takeScreenshotOfWebelement(WebDriver driver,
WebElement element, String Destination) throws Exception {
File v = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
BufferedImage bi = ImageIO.read(v);
org.openqa.selenium.Point p = element.getLocation();
int n = element.getSize().getWidth();
int m = element.getSize().getHeight();
BufferedImage d = bi.getSubimage(p.getX(), p.getY(), n, m);
ImageIO.write(d, “png”, v);

FileUtils.copyFile(v, new File(Destination));
}

public static void setWindowSize(int Dimension1, int dimension2) {
driver.manage().window().setSize(new Dimension(Dimension1, dimension2));

}

public static void takeScreenshotMethod(String Destination)
throws Exception {
File f = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(f, new File(Destination));
}

public static void pressKeyDown(WebElement element) {
element.sendKeys(Keys.DOWN);
}

public void pressKeyEnter(WebElement element) {
element.sendKeys(Keys.ENTER);
}

public static void pressKeyUp(WebElement element) {
element.sendKeys(Keys.UP);
}

public static void moveToTab(WebElement element) {
element.sendKeys(Keys.chord(Keys.ALT, Keys.TAB));
}

public static void handleHTTPS_IEbrowser() {
driver.navigate().to(
“javascript:document.getElementById(‘overridelink’).click()”);
}

public static void handleHTTPS_Firefox() {
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(false);
driver = new FirefoxDriver(profile);
}

public static void waitTillPageLoad(int i) {

driver.manage().timeouts().pageLoadTimeout(i, TimeUnit.SECONDS);

}

public static void clickAllLinksInPage(String destinationOfScreenshot)
throws Exception {

List<WebElement> Links = driver.findElements(By.tagName(“a”));
System.out.println(“Total number of links :” + Links.size());

for (int p = 0; p < Links.size(); p++) {
System.out.println(“Elements present the body :”
+ Links.get(p).getText());
Links.get(p).click();
Thread.sleep(3000);
System.out.println(“Url of the page ” + p + “)”
+ driver.getCurrentUrl());
takeScreenshotMethod(destinationOfScreenshot + p);
navigate_back();
Thread.sleep(2000);
}

}

public static void keyboardEvents(WebElement webelement, Keys key,
String alphabet) {
webelement.sendKeys(Keys.chord(key, alphabet));

}

public static void navigate_forward() {
driver.navigate().forward();
}

public static void navigate_back() {
driver.navigate().back();
}

public static void refresh() {
driver.navigate().refresh();
}

public static void waitMyTime(int i) {
driver.manage().timeouts().implicitlyWait(i, TimeUnit.SECONDS);

}

public static void clearTextField(WebElement element) {
element.clear();

}

public static void clickWebelement(WebElement element) {
try {
boolean elementIsClickable = element.isEnabled();
while (elementIsClickable) {
element.click();
}

} catch (Exception e) {
System.out.println(“Element is not enabled”);
e.printStackTrace();
}
}

public static void clickMultipleElements(WebElement someElement,
WebElement someOtherElement) {
Actions builder = new Actions(driver);
builder.keyDown(Keys.CONTROL).click(someElement)
.click(someOtherElement).keyUp(Keys.CONTROL).build().perform();
}

public static void highlightelement(WebElement element) {
for (int i = 0; i < 4; i++) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(
“arguments[0].setAttribute(‘style’, arguments[1]);”,
element, “color: solid red; border: 6px solid yellow;”);
js.executeScript(
“arguments[0].setAttribute(‘style’, arguments[1]);”,
element, “”);

}

}

public static boolean checkAlert_Accept() {
try {
Alert a = driver.switchTo().alert();
String str = a.getText();
System.out.println(str);

a.accept();
return true;

} catch (Exception e) {

System.out.println(“no alert “);
return false;

}
}

public static boolean checkAlert_Dismiss() {
try {
Alert a = driver.switchTo().alert();
String str = a.getText();
System.out.println(str);

a.dismiss();
return true;

} catch (Exception e) {

System.out.println(“no alert “);
return false;

}
}

public static void scrolltoElement(WebElement ScrolltoThisElement) {
Coordinates coordinate = ((Locatable) ScrolltoThisElement)
.getCoordinates();
coordinate.onPage();
coordinate.inViewPort();
}

public static void checkbox_Checking(WebElement checkbox) {
boolean checkstatus;
checkstatus = checkbox.isSelected();
if (checkstatus == true) {
System.out.println(“Checkbox is already checked”);
} else {
checkbox.click();
System.out.println(“Checked the checkbox”);
}
}

public static void radiobutton_Select(WebElement Radio) {
boolean checkstatus;
checkstatus = Radio.isSelected();
if (checkstatus == true) {
System.out.println(“RadioButton is already checked”);
} else {
Radio.click();
System.out.println(“Selected the Radiobutton”);
}
}

// Unchecking
public static void checkbox_Unchecking(WebElement checkbox) {
boolean checkstatus;
checkstatus = checkbox.isSelected();
if (checkstatus == true) {
checkbox.click();
System.out.println(“Checkbox is unchecked”);
} else {
System.out.println(“Checkbox is already unchecked”);
}
}

public static void radioButton_Deselect(WebElement Radio) {
boolean checkstatus;
checkstatus = Radio.isSelected();
if (checkstatus == true) {
Radio.click();
System.out.println(“Radio Button is deselected”);
} else {
System.out.println(“Radio Button was already Deselected”);
}
}

public static void dragAndDrop(WebElement fromWebElement,
WebElement toWebElement) {
Actions builder = new Actions(driver);
builder.dragAndDrop(fromWebElement, toWebElement);
}

public static void dragAndDrop_Method2(WebElement fromWebElement,
WebElement toWebElement) {
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(fromWebElement)
.moveToElement(toWebElement).release(toWebElement).build();
dragAndDrop.perform();
}

public static void dragAndDrop_Method3(WebElement fromWebElement,
WebElement toWebElement) throws InterruptedException {
Actions builder = new Actions(driver);
builder.clickAndHold(fromWebElement).moveToElement(toWebElement)
.perform();
Thread.sleep(2000);
builder.release(toWebElement).build().perform();
}

public static void hoverWebelement(WebElement HovertoWebElement)
throws InterruptedException {
Actions builder = new Actions(driver);
builder.moveToElement(HovertoWebElement).perform();
Thread.sleep(2000);

}

public static void doubleClickWebelement(WebElement doubleclickonWebElement)
throws InterruptedException {
Actions builder = new Actions(driver);
builder.doubleClick(doubleclickonWebElement).perform();
Thread.sleep(2000);

}

public static String getToolTip(WebElement toolTipofWebElement)
throws InterruptedException {
String tooltip = toolTipofWebElement.getAttribute(“title”);
System.out.println(“Tool text : ” + tooltip);
return tooltip;
}

public static void selectElementByNameMethod(WebElement element, String Name) {
Select selectitem = new Select(element);
selectitem.selectByVisibleText(Name);
}

public static void selectElementByValueMethod(WebElement element,
String value) {
Select selectitem = new Select(element);
selectitem.selectByValue(value);
}

public static void selectElementByIndexMethod(WebElement element, int index) {
Select selectitem = new Select(element);
selectitem.selectByIndex(index);
}

public static void clickCheckboxFromList(String xpathOfElement,
String valueToSelect) {

List<WebElement> lst = driver.findElements(By.xpath(xpathOfElement));
for (int i = 0; i < lst.size(); i++) {
List<WebElement> dr = lst.get(i).findElements(By.tagName(“label”));
for (WebElement f : dr) {
System.out.println(“value in the list : ” + f.getText());
if (valueToSelect.equals(f.getText())) {
f.click();
break;
}
}
}
}

public static void downloadFile(String href, String fileName)
throws Exception {
URL url = null;
URLConnection con = null;
int i;
url = new URL(href);
con = url.openConnection();
File file = new File(“.//OutputData//” + fileName);
BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));
while ((i = bis.read()) != -1) {
bos.write(i);
}
bos.flush();
bis.close();
}

public static void navigateToEveryLinkInPage() throws InterruptedException {

List<WebElement> linksize = driver.findElements(By.tagName(“a”));
int linksCount = linksize.size();
System.out.println(“Total no of links Available: ” + linksCount);
String[] links = new String[linksCount];
System.out.println(“List of links Available: “);
// print all the links from webpage
for (int i = 0; i < linksCount; i++) {
links[i] = linksize.get(i).getAttribute(“href”);
System.out.println(linksize.get(i).getAttribute(“href”));
}
// navigate to each Link on the webpage
for (int i = 0; i < linksCount; i++) {
driver.navigate().to(links[i]);
Thread.sleep(3000);
System.out.println(driver.getTitle());
}
}
}