Showing posts with label TestNG Tutorials. Show all posts
Showing posts with label TestNG Tutorials. Show all posts

Cross Browser Testing using Selenium WebDriver

Cross Browser Testing using Selenium WebDriver to run Test Scripts in different browsers like Google Chrome,Firefox ,Internet Explorer etc at a same time then we have to use TestNG Framework for Automating Cross Browser Testing using Selenium WebDriver.

What is Cross Browser Testing?

Cross Browser Testing means testing the application under test(AUT) with different browsers in order to verify all functionalities are working same in all browsers.



Problems if not done Cross Browser Testing

1.Main defect is Design issue.
2.Some functionalities not supports javascript because of browser
3.Some functionalities will not work in some browsers because of configurations.
4.Some time facing issues while uploading/Downloading file formats.
5.Faacing the problems with additional plugins like displaying grid details in applications.
6.Some functionalities will not work changing the campatability mode in browsers.

In order to over come above some problems we have to perform Cross Browser Testing for applications under test(AUT).

Pre-Requisites

1.testng.xml
2.Different browsers drivers(IE Driver,Chrome Driver etc).
3.Test Script class for test cases.
4.Declaring the browsers in a class.
5.@Parameters annotation which Describes how to pass parameters to a @Test method,where we are writing our Test Cases  i.e Test Scripts.

Example for Cross Browser Testing

Prepare textng.xml file to set up parameters for different browsers,follow same code as below.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Cross Browser Testing" preserve-order="true" verbose="2" parallel="tests">  
<parameter name="Weburl" value="http://www.google.com"></parameter>  
<test name="Internet Explorer">
<parameter name="WebBrowser" value="ie"></parameter>
<classes>
<class name="com.wiki.wiki.Cross"/>
</classes>
</test>
<test name="Google Chrome">
<parameter name="WebBrowser" value="chrome"></parameter>
<classes>
<class name="com.wiki.wikishown.Cross"/>
</classes>
</test>
<test name="Firefox">
<parameter name="WebBrowser" value="firefox"></parameter>
<classes>
<class name="com.wiki.wikishown.Cross"/>
</classes>
</test> 
</suite> 

Now create two classes one class is for driver initialization and Browser setting and second clas is for Test Scripts under @Test anotaitions,follow below classes
Create SelDriver.java class to initialize the driver and browsers set up as below

package com.wiki.seln;
import java.util.concurrent.TimeUnit;
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.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;

public class SelDriver {
public static WebDriver driver;
static String baseUrl;

@BeforeTest
@Parameters("WebBrowser")
public void setup(String WebBrowser){

//Adding verfication point using IF Condition
if(WebBrowser.equalsIgnoreCase("firefox")){
driver = new FirefoxDriver();

}else if(WebBrowser.equalsIgnoreCase("ie")){

//For ie browser we have to use System.SetProperty
System.setProperty("webdriver.ie.driver", "F:\\Java_Applications\\Zip Files\\IEDriverServer.exe");
driver = new InternetExplorerDriver();

}else if(WebBrowser.equalsIgnoreCase("chrome")){
//For Google chrome browser we have to use System.setProperty and Chrome Driver
System.setProperty("webdriver.chrome.driver", "F:\\Java_Applications\\Zip Files\\chromedriver.exe");
driver = new ChromeDriver();

}
//Maximize the windows of all browsers
driver.manage().window().maximize();

}
@AfterTest
public void tearDown(){
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

}

}

Now i am using Wikishown class and using inheritance wit the help of extends keyword as below

package com.wiki.seln;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class Cross extends SelDriver {

@Test(priority=1)
@Parameters("Weburl")
public void testMethod(String Weburl){

//Navigate to URL and Weburl is taking from testng.xml file
driver.navigate().to(Weburl);
//wait until page loads
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.liknText("Manual Testing")).click();
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
driver.findElement(By.linkText("Selenium")).click();

}

}

Above in two classes i have used @Parameters annotation to call parameter name from xml file.Now run xml file as run as -- TestNG Suite then it will run all @Test methods in a class and displays test execution results in Console as well as Test NG icon.

How to Add Screenshots to TestNG Report

How to add screenshot to TestNG Report example post provides complete real time experience coding and Testing is an activity to verify expected results.While Testing application using Selenium Testing it is very important to capture screenshot of application in order to verify any error is occurred in application while selenium script execution.

Manual testers takes screenshot using print screen (PrtSc) keyboard button or using any third party tools in order to log a defect in a Test Management tools for full proof.However coming to Selenium Automation Testing or Automatino Testing taking screenshot and using already taken screenshot in test reports is different.

How to Add Screenshots to TestNG Report

In this post you'll learn exactly how to take the screenshot and save the screenshot with different name or with timestamp and add those screenshots to TestNG Report OR Results in HTML reports.

Trending Posts

Write Test Cases PASS/FAIL in Excel using Selenium
Complete XPATH Tutorial examples
Selenium Data Driven Framework
Selenium HTML Reports Generation
Read Data From Properties files


Please follow below steps to perform the task.

1.Create the method for screenshot
2.Call the method in another classes to use in @Test methods
3.Store the Screenshot in a seperate folder with different name or timestamp.


Class 1:

package com.sel.Selenium.Practise;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
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.chrome.ChromeDriver;
import org.testng.Reporter;
import org.testng.annotations.BeforeTest;


public class SelDriver {

public static WebDriver driver;
String baseurl;
public static Properties property;

@BeforeTest
public void openBrowser() throws IOException{

//Reporter .log is a Logger given by TestNG framework.
Reporter.log("Screenshot Capture in TestNG Results Started"); 
System.setProperty("webdriver.chrome.driver", "F:\\Java_Applications\\Zip Files\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
Reporter.log("Chrome Browser is Maximized");
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);

}

public void screenCapture() throws IOException{

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
File screenshotName = new File ("E:\\Screenshots\\"+System.currentTimeMillis()+"_"+".png");
FileUtils.copyFile(scrFile, screenshotName);
Reporter.log("<br><img src='"+screenshotName+"' height='300' width='300'/><br>");

}

}


Class 2:

package com.sel.Selenium.Practise;
import java.io.IOException;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.Test;

public class GoogleSite extends SelDriver {

@Test//Test Case one
public void seleniumElements() throws InterruptedException, IOException{

driver.get("https://learn-selenium-automation-testing.blogspot.in");

System.out.println("Open Google site");
Reporter.log("Selenium Site is Open");

screenCapture();//Calling same method created in first class
Reporter.log("Screenshot Capture is done");  
String Title=driver.getTitle();
Assert.assertEquals(Title, "Learn Selenium Automation Testing");
Reporter.log("Verifying the Page with Page Title");
Reporter.log("Screenshot Capture in TestNG Results ended.");
}

}


Now run the second class as TestNG Test ,you'll observe screenshot will added in specific folder with time-stamp ,refresh the project and open index.html file to check screenshot is added ot not in TestNG Results under Reporter Output link of TestNG Report.

Please try above code and let me know in case you're facing any issues.In case code is working fine,Please provide your feedback on below comment box.Thank you for reading and Have a Greate Selenium WebDriver Scripting.

Trending Posts

Write Test Cases PASS/FAIL in Excel using Selenium 
Complete XPATH Tutorial examples
Selenium Data Driven Framework
Selenium HTML Reports Generation
Read Data From Properties files

Java Lang NullPointerException in Selenium

Java Lang NullPointerException in Selenium,While running the selenium test scripts you'll face some challenges with the test scripts,in that challenges this is the main important exception,not able to understand why it is displaying and most of the time you'll think that it is raised because of element is not identifying by the Selenium,that is not the proper answer.

Java Lang NullPointerException in Selenium

Java Lang NullPointerException in Selenium


Also Read:


Write TestCase is PASS/FAIL In seleniumTestNG Classpath errorSession ID is null using webdriver after calling quitHow to send extent reports in email with screenshots





Java Lang NullPointerException in Selenium

When coming to Java Lang NullPointerException in Selenium,when passing single webdriver instance to multiple classes,you'll face this type of problems.Please read below instructions  to resolve the same issue in Selenium.

SelDriver Class:



package com.sel.Selenium.Practise;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeSuite;

public class SelDriver {  
 public WebDriver driver;
 String baseurl = "http://www.google.co.in";  
 
 @BeforeSuite
 public void openBrowser(){
  
  driver = new FirefoxDriver();
  //driver = new HtmlUnitDriver();
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
  
 } 
}

GoogleSite Class:



package com.sel.Selenium.Practise;
import org.testng.Assert;
import org.testng.annotations.Test; 
public class GoogleSite extends SelDriver {
 
 @Test
 public void seleniumElements() throws InterruptedException{
  
  driver.get(baseurl);
  System.out.println("Open Google site");
  
  String Title=driver.getTitle();
  Assert.assertEquals(Title, "Google");
  
  try {
        Assert.assertEquals(driver.getTitle(), "Google's");
      } catch (Error e) {
        System.out.println(e.getCause());
      }   
 } 
}

I', extending the class from SelDriver main class to use WebDriver instance,But when running the above class,you'll face same issue i.e Java.Lang.NullPointerException for some methods.In order to resolve this issue,you need to add static for WebDriver declaration as below.



package com.sel.Selenium.Practise;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeSuite;

public class SelDriver {
 
 public static WebDriver driver;
 String baseurl = "http://www.google.co.in";  
 
 @BeforeSuite
 public void openBrowser(){
  
  driver = new FirefoxDriver();
  //driver = new HtmlUnitDriver();
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
  
 } 
}


Before Static Method Test Results:




After Changes - Test Results

[TestNG] Running:
  E:\QTPTutorials\Selenium_Workspace\Selenium_Tutorials\testng.xml

Open Google site
null
driver=FirefoxDriver: firefox on WINDOWS (f2f86423-9806-4b4a-ae92-7504e3db59be)
Enter Search Keyword
Clear Enter Keyword
clear works

===============================================
GoogleTestSuite
Total tests run: 2, Failures: 0, Skips: 0
===============================================

TestNG Test Results


Please provide your valuable comments on this solution in case it is resolved your java.lang.nullpointer exception in Selenium.

Mouse hover action in Selenium Webdriver

Mouse hover action in Selenium Webdriver,While working with web application menus you will face a problem that mouse hover,once mouse hover then only remaining menus will be displayed.In this post you will learn Mouse hover action in selenium webdriver using Web elements ,Actions classes in Selenium Web Driver.Below are the way of doing this is by using Action in class.

Mouse hover action in Selenium WebDriver


Mouse hover action in Selenium Webdriver

Method 1:

Here directly using link Text to check mouse hover for main menu or sub menu to identify the elements in webpage.

WebElement element = driver.findElement(By.linkText("More.."));
Actions action = new Actions(driver);
action.moveToElement(element).build().perform();
driver.findElement(By.linkText("SQL")).click();

Some times it will not work then we can use another method as below to select SQL link from More.. menu according to above menu.

Also Read

Datadriven Framework using selenium
Verify element is enable in Selenium
Read Data From properties file using Selenium
Launch Firefox Browser using GeckoDriver
Selenium-Testng examples to execute multiple classes
Selenium WebDriver Methods
Generate HTML Reports using Selenium

For some applications mouse over will work upto certain fraction of seconds at that situation we can go for below method easily to identify the elements.This method will work deffinately with the help of action.moveToElement(element).click().build.perform

package com.gmail.account;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import org.apache.tools.ant.taskdefs.Exit;
import org.openqa.selenium.By;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;

public class MouseOver{

WebDriver driver;
String baseUrl;

@Test
public void mouseHover(){

driver = new FirefoxDriver();
String baseUrl = "http://www.wikishown.com";
driver.get(baseUrl);
driver.manage().window().maximize();
//Use Action
Actions action = new Actions(driver);
//Mouse over on elements using WebElments
WebElement element = driver.findElement(By.linkText("More.."));
//Now mouse should move to particular element
action.moveToElement(element).click().build().perform();
Thread.sleep(2000);
//Identifying the SubMenu and click on Subbmenu
action = new Actions(driver);
WebElement subelement=driver.findElement(By.linkText("SQL"));
//Thread.sleep(5000);
action.moveToElement(subelement).click().build().perform();

}

}

Run above script as Right Click on Script - Run As  - TestNG Test.

Conclusion:

I am expecting method 2 is very useful in your projects,in case it is working please provide your valuable comments and suggestions and please feel free to contact me through comment.Thank you for reading.

Selenium-Testng examples to execute multiple classes

This summary is not available. Please click here to view the post.

TestNG - Execute multiple classes in testng examples

TestNG - Execute multiple classes in TestNG examples,in testng.xml file you can execute or run multiple classes under one test or Test Suite with the help of classes tags ,TestNG is a test framework to run all your multiple classes in a sequential manner,Let's see how to execute or run multiple classes in TestNG with examples as below.


TestNG - Execute multiple classes in TestNG examples


In this examples i am taking three java classes which will contains Selenium WebDriver driver initialization ,Normal Mail site opening and Sample registration class.Let's write the code step by step and execute the same.

Must Read:

Session ID is null using webdriver after calling quit
How to send extent reports in email with screenshots
Write Test Cases PASS or FAIL using Selenium
TESTNG Cannot find classpath error
Read data from properties file in selenium
Run Selenium scripts using Command Line
Run Selenium Scripts using Runnable JAR
TOP Selenium Interview Questions asked in MNC

Selenium XPATh tutorial step by step



Selenium WebDriver class



package com.mail.Mails;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;


public class SeleniumWebdrivers {

static WebDriver driver;
static String baseUrl="http://www.ebay.in";

@BeforeSuite
public void open_browser(){

//Open Firefox Browser with the help of Firefox Driver
driver = new FirefoxDriver();
driver.manage().window().maximize();
//Open baseurl with the help of get method
driver.get(baseUrl);

try {
Thread.sleep(2500);

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();

}

}

@AfterSuite
public void close_browser(){
driver.quit();
}

}

Search Product class

In this class we are using extends keywords to class driver objects into other classes,please read more details about How to pass driver instance to other classes.
package com.mail.Mails;

import org.openqa.selenium.By;

import org.testng.annotations.Test;

public class Searchproduct extends SeleniumWebdrivers {

@Test

public void Search_product(){
//Enter Keywords in Search box
driver.findElement(By.id("gh-ac")).sendKeys("Mobiles");
//Click on Go button
driver.findElement(By.id("gh-btn")).click();
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();}

}

}


Products class



package com.mail.Mails;

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

public class ProductDescp extends SeleniumWebdrivers {

@Test

public void product_Descriptoin(){

//Count number of products displayed on displayed page as per

//Search Criteria

String listingcount=driver.findElement(By.xpath("/html/body/div[5]/div[2]/div
[1]/div[1]/div/div[1]/div/div[2]/div/div/span[1]")).getText();
//Print number of listing counts

String count = listingcount.replaceAll("\\D+","");

System.out.println("Listed number of mobiles are : "+count);

//Using Parseint methods to change string into Integer

int counts = Integer.parseInt(count);

//Validating listing products count with if condition

if(counts > 0){

System.out.println("Number of listing are greater than zero :"+ "counts "+" Test case is PASS");

}else{

System.out.println("Number of listing products are lessthan zero : Test Case is FAIL");

}

}

}



TestNG.XML file



<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="Suite1" verbose="1" >

<test name="Eproducts">

<classes>

<class name="com.mail.Mails.Searchproduct"/>

<class name="com.mail.Mails.ProductDescp"/>

</classes>

</test>

</suite>



testng xml


Test Results


[TestNG] Running:
E:\QTP Tutorials\Selenium Automation\MailsAutomation\testng.xml

Listed number of mobiles are : 1851
Number of listing are greater than zero :counts Test case is PASS

===============================================
Suite1
Total tests run: 2, Failures: 0, Skips: 0
===============================================


Execute Multiple Classes in TestNG Examples



What have you learned?

1.What is TestNG XML file
2.How to create TestNG XML file with number of classes.
3.How to create driver objects and use in other classes.

Please share my posts and provide your valuable comments ,i hope you like my post.Thank you for reading.

TestNG - Cannot find class in classpath Error

TestNG - Cannot find class in classpath Error/exception in Java displaying while running your java program using TestNG framework. TestNG framework provides facility to execute multiple classes and multiple methods.



TestNG - Cannot find class in classpath Error

MY BLOG MOVED TO NEW WEBSITE ,Given each and every SELENIUM TOPICS with REAL TIME examples,PLEASE read and become experienced persons in Selenium Automation Testing.