Automation Using Selenium Webdriver

Monday, 14 November 2016

Find top two maximum numbers in a array java

  • Hi Friends today we will discuss about how to find top two maximum numbers in an array using java program.
  • For this we have written separate function to perform logic
  • findTwoMaxNumbers method takes integer  array as an argument
  • Initially take two variables to find top to numbers and assign to zero.
  • By using for each loop iterating array and compare current value with these values
  • If our value is less than current array value then assign current value to max1 
  • And assign maxone to maxtwo because maxtwo should be second highest.
  • After completion of all iterations maxone will have top value and maxtwo will have second maximum value.
  • Print first maximum and second maximum values.
  • So from main method create array and pass to findTwoMaxNumbers(int [] ar).


Program #1: Java interview programs to practice: find top two maximum numbers in an array without recursion 

package arraysInterviewPrograms.java;
public class FindTopTwo {
public void findTwoMaxNumbers(int[] array){
       
 int maxOne = 0;
 int maxTwo = 0;
for(int i:array){
    if(maxOne < i){
           maxTwo = maxOne;
           maxOne =i;
     } else if(maxTwo < i){
                maxTwo = i;
     }
}
        
  System.out.println("First Maximum Number: "+maxOne);
  System.out.println("Second Maximum Number: "+maxTwo);
}
     
public static void main(String a[]){
        int num[] = {4,23,67,1,76,1,98,13};
        FindTopTwo obj = new FindTopTwo();
        obj.findTwoMaxNumbers(num);
        obj.findTwoMaxNumbers(new int[]{4,5,6,90,1});
}
}


Output:


First Maximum Number: 98
Second Maximum Number: 76
First Maximum Number: 90
Second Maximum Number: 6

Calling static method from non static method in java

  • Static means class level and non static means object level.
  • Non static variable gets memory in each in every object dynamically.
  • Static variables are not part of object and while class loading itself all static variables gets memory.
  • Like static variables we have static methods. Without creating object we can access static methods.
  • Static methods are class level. and We can still access static methods in side non static methods.
  • We can call static methods without using object also by using class name.
  • And the answer to the question of  "is it possible to call static methods from non static methods in java" is yes.
  • If we are calling a static method from non static methods means calling a single common method using unique object of class which is possible. 


Program #1: Java example program to call static method from non static method. 


;
public class StaticMethodDemo {
void nonStaticMethod(){
        
        System.out.println("Hi i am non static method");
        staticMethod();
 }
    
 public static void staticMethod(){
        
        System.out.println("Hi i am static method");
  }
    
 public static void main(String[] args) {
        StaticMethodDemo obj= new StaticMethodDemo();
        
        obj.nonStaticMethod();
    }
}
 Output:

Hi i am non static method
Hi i am static method

In the above program we have created object of the class and called a non static method on that object and in side non static method called a static method.
So it is always possible to access static variables and static methods in side non static methods

 Program #2: Java example program to call static method from non static method.



Sunday, 13 November 2016

Collections List

List Interface:
List allows Duplicate Elements.
List having index.
List allows n number of null values.
List will display Insertion order with index.
List having classes like :
Vector
ArrayList
LinkedList
Vector:
Vector is a legacy class.
Vector is synchronized.
Vector initial capacity is 10.
Vector allows n number of null values
Vector can be accessible by index.
Vector allows Duplicate Elements.
Program for Vector:

package com.instanceofjavaforus;
import java.util.Enumeration;

import java.util.List;

import java.util.Vector;



public class A{

 public static void main(String[] args) {

 

 Vector vector=new Vector();



 vector.add("india");

 vector.add("jagan");

 vector.add("sam");

 vector.addElement(null);

 vector.addElement(null);
 
  Enumeration em=vector.elements();
 while(em.hasMoreElements()){
  System.out.println(em.nextElement());
 
 }
 }

}
Output:

india
jagan
sam
null

null



ArrayList:

ArrayList is not Synchronized.
Arraylist also allows Duplicate Elements.
ArrayList allows n number of null values.
Arraylist  having insertion order with index.
For retrieve purpose ArrayList is best choice.
ArrayList having Randaom Access Nature.
Program for ArrayList ;



package com.instanceofjava;
import java.util.ArrayList;
import java.util.ListIterator;

import java.util.List;



public class A{

 public static void main(String[] args) {

 

             ArrayList arrayList=new ArrayList();




 arrayList.add("jagan");

 arrayList.add("jagan");

 arrayList.add("upendra");

 arrayList.add(null);

 arrayList.add(null);
 
  ListIterator it=arrayList.listIterator();
 while(it.hasNext()){
  System.out.println(it.hasNext());
 
 }
 }
}

Output:
jagan
jagan
upendra
null
null

LinkedList:

LinkedList is not synchronized.
LinkedList allows n number of null values.
LinkedList allows Duplicate Elements.
LinkedList  having insertion order with index.
Insertion and Deletion purpose LinkedList is better choice.
LinkedList Follows Doubly linked list Structure.
Program for LinkedList:


package com.instanceofjava;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.List;

public class A{

 public static void main(String[] args) {

   LinkedList linkedList=new LinkedList();




 linkedList.add("jagan");

 linkedList.add("jagan");

 linkedList.add("naresh");

 linkedList.add(null);

 linkedList.add(null);


  ListIterator it=linkedList.listIterator();
  while(it.hasNext()){
  System.out.println(it.hasNext());
 
 }
 }
}

Output:


jagan
jagan
naresh
null
null
In List interface if you want  to add elements we can use add() method.
If you want  to remove elements we can use remove() method.

Using Keys Method to Perform Keyboard Actions in Suggestions List Box

There’s always a need to perform keyboard actions in Suggestion List.For that purpose we  can use this ‘org.openqa.selenium.Keys’ method. Here I am sharing the Code, how to do it.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class indianrail
{
public static void main(String[] args) throws Exception
{
FirefoxDriver fd=new FirefoxDriver();
fd.get(“http://www.indianrail.gov.in&#8221;);
fd.findElement(By.linkText(“Trains between Stations”)).click();
Thread.sleep(5000);
fd.findElement(By.id(“txtStationFrom”)).sendKeys(“hyd”);
fd.findElement(By.id(“txtStationFrom”)).sendKeys(Keys.ARROW_DOWN);
fd.findElement(By.id(“txtStationFrom”)).sendKeys(Keys.ENTER);
Thread.sleep(2000);
fd.findElement(By.id(“txtStationTo”)).sendKeys(“bangalo”);
fd.findElement(By.id(“txtStationTo”)).sendKeys(Keys.ARROW_DOWN);
fd.findElement(By.id(“txtStationTo”)).sendKeys(Keys.ARROW_DOWN);
fd.findElement(By.id(“txtStationTo”)).sendKeys(Keys.ENTER);
Thread.sleep(2000);
new Select(fd.findElement(By.name(“lccp_classopt”))).selectByVisibleText(“THIRD AC”);
Thread.sleep(2000);
fd.findElement(By.name(“submit2”)).click();
}
}

Saturday, 12 November 2016

Selenium FAQs

Q. What is automation and Advantages of automation
A.The process of converting the manual test cases to test scripts by using any automation tool is known as Automation
Advantages:
1. It saves time by executing the test cases with out manual effort
2. CTC(Cost to the company) can be saved
3. We can maintain Accuracy by repeating the same task in same manner
4. Bugs can be identified
5. We can report the bugs to the developer
6. We can ensure for quality

Q. What are the components available in Selenium
A.Selenium contains 4 components
1. Selenium IDE 2. Selenium RC 3. Selenium WebDriver 4. Selenium Grid

Q. Why should we go for Selenium instead of QTP (or) How is Selenium different from commercial browser automation tools?
A.1.Selenium is an opensource automation tool
2. It supports multiple languages like Java,C#,Perl,python,Ruby,HTML and PHP
3. It supports Firefox, IE, Google chrome, Safari and Opera
4. Supports Windows, Linux and Mac
5.Supports Web and mobile Applications
6. Its very flexible and extendable

Q. What is Selenium IDE
A.1. IDE stands for integrated Development environment.
2. It is for Record and Run the Scripts
3. Selenium IDE is an add on for Firefox
4. Its accountable for user actions
5. Recorded script can be viewed in the supported languages like HTML, JAVA, C#, Ruby, Python
6. Recorded script can be run against other browsers also by using Selenium RC or Webdriver

Q. How to capture screen shot in web driver.
A.We can capture screenshot by using below two lines:
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(“D:\\screenshot.png”));

Q. How to maximize the browser in web driver.
A.driver.manage().window().maximize();

Q. How to run selenium server from command prompt.
A.1. Go to command prompt
2. Give the path, Where the selenium server is saved ex: cd E:Library
3. Use the command “java -jar selenium-server-standalone-2.42.2.jar”

Q. What is Selenium RC
A.RC stands for Remote Control. It is a server and it launches browsers. It acts as API and library. It controls the entire automation

Q. How many test cases can be automated per day.
A.It always depends on the application and test cases. But on and average we can automate 5 to 6 test cases per day. Ex: 1. For analyzing the test cases 2. Developing the script 3. Debugging and executing the script 4. Stabilizing the script

Q. What challenges you have faced with Selenium.
A.Challenge means problems or issues 1. Maintaining synchronization is a challenge in Selenium. 2. Handling Desktop, Flex, Flash elements is challenge with selenium. 3. Proving the user defined Results a challenge 4. Taking the data from the application is a challenge

Q. How to handle SSL Certificate issue in Firefox with Webdriver (or) How do you handle the secured connection error in HTTPS?
A.FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
profile.setAssumeUntrustedCertificateIssuer(false);
driver=new FirefoxDriver(profile);

Q. What is the latest version of Selenium available
A.selenium-server-standalone-2.42.3.jar

Q. How to handle SSL certication issue in IE
A.Add the below command after opening the browser.
driver.navigate().to(“javascript:document.getElementById(‘overridelink’).click()”);

Q. How to change the port number for Selenium RC
A.Syntax:   -jar  seleniumJarfileName -port anyFourdigitNo
Ex:  -jar selenium-server-standalone-2.33.0.jar -port 1234

Q. How do you start Selenium RC from command prompt?
A.1. Save the selenium jarfile (Selenium-server-standalone-2.34.0.jar) in any folder (Ex: D:/Library)
2. Open command prompt
3. Navigate to the path where you have saved the jar file and follow the below steps

D:
cd D:/Library
java -jar selenium-server-standalone-2.34.0.jar

Q. What locators available in Selenium RC
A.ID
Name
CSS (Cascade style sheet)
XPATH (Relative xpath and Absolute xpath)
Dom

Q. What locators available in Selenium Webdriver
A.ID
Name
CSS
XPath
Classname
TagName
LinkText
Partial Link Text

Q. How to create DefaultSelenium object and what parameters needs to be pass
A.DefaultSelenium selenium= new DefaultSelenium(“localhost”,4444,”*firefox”,”http://”);
localhost – It is the machine name and selenium server should be configured in the specific machine
4444 – It’s selenium port number.
*firefox – Its is the command to launch firefox
http:// – Protocol to open URL
 

Q. How many types of Xpaths are available
A.Xpath is two types:

1. Relative XPath
2. Absolute XPath

Q. • What is the difference between single and double slash in Xpath.
A.“// ” is the starting point of the Xpath.
“/” will navigate into the tag

Ex:  //html/head/body/div1/div2/……

 

Q. How to handle Alerts and Confirmation Alerts in WebDriver
A.We have to navigate to Alert or Confirmation as below,

driver.switchTo().alert()

To click OK or Cancel on Alert or Confirmation Alert then follow as below

driver.switchTo().alert().accept();  — To click OK

driver.switchTo().alert().dismiss(); — To click Cancel

 

Q. How to Handle Popup in Webdriver
A.We have to navigate to the popup as below

driver.switchTo().window(“Window Name”);

To navigate from Popup to main window

driver.switchTo().window(“Main Window Name”);

 

Q. How to handle dynamically changing popup in Webdriver
A.Dynamic means the Name is not constant. It changes frequently

Use the below approach to handle Dynamically changing popup

Set<String> s=driver.getWindowHandles();
Object popup[]=s.toArray();
driver.switchTo().window(popup[1].toString());

 

Q. Is it possible to handle multiple popups in Webdriver
A.Yes.
We can handle it by using the command

driver.getWindowHandles();

 

Q. How to capture window name
A.driver.getWindowHandle();

 

Q. How to launch Firefox, Safari and Opera with Webdriver
A.Firefox, Safari and Opera we be launch by using below commands.

WebDriver driver=new FirefoxDriver();

WebDriver  driver=new OperaDriver();

WebDriver  driver=new SafariDriver();

Q. How to launch InternetExplorer.
A.For IE, we need the supported “Internet Explorer Driver Server”. It can be downloaded from the below site:

http://docs.seleniumhq.org/download/

Below code is to launch IE.

System.setProperty(“webdriver.ie.driver”, “E:\\Library\\IEDriverServer.exe”);
driver=new InternetExplorerDriver();
driver.get(“http://gmail.com“);

 

Q. How to launch GoogleChrome
A.For GoogleChrome, We need the supported “ChromeDriver” exe file. Can be downloaded from the below site:

http://code.google.com/p/chromedriver/downloads/list

Below code is to launch GoogleChrome

System.setProperty(“webdriver.chrome.driver”, “E:\\Library\\chromedriver.exe”);
driver=new ChromeDriver();
driver.get(“http://gmail.com“);

 

Q. Brief about the Disadvantages of Selenium
A.Selenium supports Web applications. It doesn’t support Desktop applications 

Q. How to handle Deskptop, Flex and Flash objects in Selenium.
A.We can use SIKULI as a add-on for Selenium to support Desktop, Flex and Flash objects

Sikuli is an open source automation tool developed on JAVA

Can be downloaded from:https://launchpad.net/sikuli/+download

 

Q. How to take data from excel(xls) file
A.FileInputStream fi=new FileInputStream(“Path of the excel file”);

Workbook w=Workbook.getWorkbook(fi);

Sheet s=w.getSheet(0);

It will read the excel file upto the sheet. To take the data from sheet, use below command,

s.getCell(columnID, rowID).getContents())

ex: s.getCell(0, 1).getContents();

 

Q. How to create Excel file
A.FileOutputStream fo=new FileOutputStream(“Path to create xls file”);

WritableWorkbook wb=Workbook.createWorkbook(fo);

WritableSheet ws=wb.createSheet(“Results”, 0);

Label un=new Label(0,0,”Username”);

ws.addCell(un);

wb.write();

wb.close();

Q. How to print data from notepad(txt file)
A.File f=new File(“E:\\data2.txt”);

FileReader fr=new FileReader(f);

BufferedReader br=new BufferedReader(fr);

String str;

while((str=br.readLine())!=null)

{

System.out.println(str);

}

 

Q. How to create and write data into txt file
A.  File f=new File(“E:\\data2.txt”);
FileWriter fw=new FileWriter(f);
BufferedWriter bw=new BufferedWriter(fw);
bw.write(“Nagesh”);
bw.newLine();
bw.write(“hyderabad”);
bw.newLine();
bw.write(“AP”);
bw.close();
fw.close();

Q. How to take or print data from XML file
A.File fXmlFile = new File(“D://file.xml”);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println(“Root element :” + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName(“staff”);
System.out.println(“—————————-“);
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println(“\nCurrent Element :” + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println(“Staff id : ” + eElement.getAttribute(“id”));
System.out.println(“First Name : ” + eElement.getElementsByTagName(“firstname”).item(0).getTextContent());
System.out.println(“Last Name : ” + eElement.getElementsByTagName(“lastname”).item(0).getTextContent());
System.out.println(“Nick Name : ” + eElement.getElementsByTagName(“nickname”).item(0).getTextContent());
System.out.println(“Salary : ” + eElement.getElementsByTagName(“salary”).item(0).getTextContent());
}
}

 

Q. What is Ant or Apache Ant
A.Ant is a Java based build management tool.
The process of converting the source code to software system (executable code) is known as build.
There are number of steps to convert the source code to executable code. Ant will manages all the steps with Build.xml file.

Steps to convert the Source code to software:
1. Taking the source code from src repository
2. Preparing a build area
3. Compiling the source code
4. Build the compiled code to executable code

 

Q. What is Maven
A.Maven is also Java based build management tool. It is the advanced version of Ant.

 

Q. What is the differences between Ant and Maven
A.1. Maven is widely preferred than Ant. Ant is an older tool.
2. Ant doesn’t come with formal conventions such as a common project directory. Maven consists of conventions.
3. Ant is procedural, Maven is declarative. It means in Ant, you have to specify the order what should have to be done, where as Maven takes care of all the directories once the files are stored in the pom.xml file.
4. Another difference that can be seen is that Ant does not have a life cycle whereas Maven has a life cycle.
5. The scripts in Ant are not reusable where as Maven comes with reusable plugins.

 

Q. What are the disadvantages of using Selenium as testing tool
A.It doesn’t support desktop or windows based applications.
But we can overcome by using the tool SIKULI

 

Q. How do you handle Ajax controls using selenium? i. Eg. By typing in search engine how do you capture the auto suggestion
A.Ajax control means when we enter some text in the google text box, it display the auto suggested values. That text box is an ajax control.
Type the value in the textbox and capture all the suggested values in a string.
Split the string and take the values

 

Q. How do you select the 2nd item in a List box or drop down.
A.new Select(driver.findElement(By.id(“id”))).selectByIndex(index);

 

Q. Brief about your framework
A.Its Hybrid framework where its a combination of Keyword driven (TestNG) and DataDriven framework.
Advantage of Hybrid framework is, we can utilize the advantages of both Keyword driven and Datadriven frameworks

 

Q. What is the difference between assert and Verify Commands?
A.Verify command will not stop execution of test case if verification fails. It will log an error and proceed with execution of rest of the test case.
Assert command will stop execution of test case if verification fails. It will log an error and will not proceed with execution of rest of the test case

 

Q. Explain about your reporting method
A.Bug Reporting is always a manual process. Getting the test report from the automation tool and analyze the report for bugs. If identified, report the bugs by using QC or Bugzilla or JIRA

 

Q. What is the difference between Selenium RC and Webdriver
A.1. We can access all the latest browsers
2. Not necessary to start Selenium server to run the webdriver programs
3. Webdriver by default maintains page load synchronization, for page refresh we need to handle it
4. Its having auto scroll down action into the application while executing the script
5. We can develop both webdriver commands and RC in a single class
6. We can effectively take the information from application

 

Q. What are all things can not be done through selenium IDE
A.We can’t perform below testings
1. Regression testing
2. Retesting
3. Static Testings like GUI and Validations
4. DB Testing
5. It doesn’t provide Test Report

 

Q. Brief about Selenium Grid.
A.It is for parallel execution. We can launch all the browsers parallelly and the scripts can be executed on it parallelly

 

Q. How to use selenium for performance testing
A.Selenium is functional testing automation tool. Its not for performance testing. We can generate only the load by using Selenium.

 

Q. How to get all the links in http://google.co.in
A.Link means anchor tag in any application.
Identify all the links by using FindElements and tagname.
Get all the links to List variable and take the targetted link by using for loop and if condition

 

Q. Is it possible to handle multiple popups in selenium?
A.Yes we can handle it with the command getWindowHandles().
Take all the window names into Set<String> variable and convert it to array.
Use the array index to navigate to specific window by using driver.switchTo().window(ArrayIndex);

 

Q. Difference between Junit and TestNg framework
A.JUnit Vs TestNG

1. We need to implement all the test methods very independently in Junit. Not necessary in TestNg
2. JUnit contains very limited annotations like @Beforeclass, @Before, @Test, @After and @AfterClass. TestNG  contains multiple annotations like @BeforeSuite, @BeforeTest, @Beforeclass, @BeforeMethod, @Test, @AfterMethod @AfterClass, @AfterTestand @AfterSuite
3. TestNG provides html result file by default where as in JUnit it wont provide html result file by default

 

Q. If the default port of selenium is busy then which port you use?
A.Selenium by default uses 4444 port no. If the port is already used by any other server then we can change it to any other 4 digit no.
Ex: 5555 or 1234 or 6666

 

Q. How much time we can save with automation
A.It always depends on the project and test cases. But on and average we can save around 50% to 60% of the time.

 

Q. What is automation Lifecycle or Automation approach or automation plan
A.1. Do the POC for the project
2. Execute or review all the manual test cases to get the functional knowledge of the project and to identify the test cases for automation
3. Develop the framework
4. Prepare the test scripts for all the identified test cases
5. Integrate the scripts with Framework for execution
6. Before executing identify the build changes, if available update the scripts
7. Execute the scripts and capture all the results in seperate folder
8. Analyze the test report and identify the bugs
9. Report the bugs manually to the developer by using some reporting tool

 

Q. Write a program to get all the text boxes in mail.in register page with webdriver
A.  List<WebElement> str=driver.findElements(By.tagName(“textbox tagname”));
System.out.println(str.size());

for (int i = 0; i < str.size(); i++) {
System.out.println(str.get(i).getAttribute(“id”)); //To prnt ids
}

 

Q. How to execute scripts on other machines Remotely
A.URL url = new URL( “http”, “localhost”, 4444, “/wd/hub” );
DesiredCapabilities capabilities =DesiredCapabilities.internetExplorer(); capabilities.setJavascriptEnabled(true); WebDriver driver = new RemoteWebDriver(url,capabilities); driver.get(“http://www.google.com”);

Note: Provide IP address of other machines instead of localhost

 

Q. How to Mouse over on one element by using webdriver
A.      WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get(“http://spicejet.com”);
Actions a=new Actions(driver);
WebElement str=driver.findElement(By.linkText(“About Us”));
a.moveToElement(str).build().perform();

 

Q. How to Scroll down and Scroll up in the browser
A.      WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get(“http://spicejet.com”);
Actions a=new Actions(driver);
a.keyDown(Keys.CONTROL).sendKeys(Keys.END).build().perform();
Thread.sleep(1000);
a.keyDown(Keys.CONTROL).sendKeys(Keys.HOME).build().perform();
a.keyDown(Keys.ALT).sendKeys(Keys.F1).build().perform();

Friday, 11 November 2016

Handle Web Table Dynamically In Selenium WebDriver

Whenever the pagem loads its take the table data dynamically and get the table data.

In this Example am going to take table data for the below table.




Source code :

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class testpins {
WebDriver driver = new FirefoxDriver();

@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://www.moneycontrol.com/");
}

@AfterTest
public void tearDown() throws Exception {
driver.quit();
}

@Test
public void Handle_Dynamic_Webtable() {

// To locate table.
WebElement mytable = driver.findElement(By.xpath("//*[@id='tblrMC']"));
// To locate rows of table.
List<WebElement> rows_table = mytable.findElements(By.tagName("tr"));
// To calculate no of rows In table.
int rows_count = rows_table.size();

// Loop will execute till the last row of table.
for (int row = 0; row < rows_count; row++) {
// To locate columns(cells) of that specific row.
List<WebElement> Columns_row = rows_table.get(row).findElements(
By.tagName("td"));
// To calculate no of columns(cells) In that specific row.
int columns_count = Columns_row.size();
System.out.println("Number of cells In Row " + row + " are "
+ columns_count);

// Loop will execute till the last cell of that specific row.
for (int column = 0; column < columns_count; column++) {
// To retrieve text from that specific cell.
String celtext = Columns_row.get(column).getText();
System.out.println("Cell Value Of row number " + row
+ " and column number " + column + " Is " + celtext);
}
System.out
.println("--------------------------------------------------");
}
}
}

If you run the above code your output look like this,

Number of cells In Row 0 are 0
--------------------------------------------------
Number of cells In Row 1 are 5
Cell Value Of row number 1 and column number 0 Is Gabriel India
Cell Value Of row number 1 and column number 1 Is Nov 5th 2014
Cell Value Of row number 1 and column number 2 Is 83
Cell Value Of row number 1 and column number 3 Is 99.25
Cell Value Of row number 1 and column number 4 Is 19.00
--------------------------------------------------
Number of cells In Row 2 are 5
Cell Value Of row number 2 and column number 0 Is SKF India
Cell Value Of row number 2 and column number 1 Is Oct 8th 2014
Cell Value Of row number 2 and column number 2 Is 1116
Cell Value Of row number 2 and column number 3 Is 1472.50
Cell Value Of row number 2 and column number 4 Is 31.90
--------------------------------------------------
Number of cells In Row 3 are 5
Cell Value Of row number 3 and column number 0 Is Sonata Software
Cell Value Of row number 3 and column number 1 Is Oct 7th 2014
Cell Value Of row number 3 and column number 2 Is 127
Cell Value Of row number 3 and column number 3 Is 153.05
Cell Value Of row number 3 and column number 4 Is 20.37
--------------------------------------------------
Number of cells In Row 4 are 5
Cell Value Of row number 4 and column number 0 Is IFCI
Cell Value Of row number 4 and column number 1 Is Sep 24th 2014
Cell Value Of row number 4 and column number 2 Is 35
Cell Value Of row number 4 and column number 3 Is 43.30
Cell Value Of row number 4 and column number 4 Is 25.51
--------------------------------------------------
Number of cells In Row 5 are 5
Cell Value Of row number 5 and column number 0 Is Minda Industries
Cell Value Of row number 5 and column number 1 Is Sep 15th 2014
Cell Value Of row number 5 and column number 2 Is 434
Cell Value Of row number 5 and column number 3 Is 655.00
Cell Value Of row number 5 and column number 4 Is 51.03
--------------------------------------------------
PASSED: Handle_Dynamic_Webtable

Thursday, 10 November 2016

Generate Customized ExcelReports Using TestNG in Selenium

There are many ways to Generate Reports in Selenium. Now I’d like to generate an excel reports. This report will give you the number test cases has been Passed and Failed or Skipped. It’s quite simple to generate this report. All you need to do is just giving a Proper Name and Destination Path (if you’re using the latest jar 4.0.1).
Note: TestNG is required. Without testNG this code won’t work.
There are few steps to be followed to generate Excel Reports. Here I am sharing the snippet.
Download the latest Jar from here ExcelReportGenerator version 4.0.1. Add this Jar into your project BuildPath.
If You’re using Jar 4.0.1 version then you can specify the desired location and File name in the code itself.
Follow the Steps Specified :
Step1: Create a Package ‘ExcelResults’ under your Project (Optional, if you’re using 4.0.1 version).
step2: Create  the test cases 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.generateExcelReport(“MyProject.xls”, “D:\\workspace”);
}
}
Step5: Refresh the package ‘ExcelResults’ (If you’re using older version).
Step5 : Results will be generated at your desired path given. (If you’re using 4.0.1 version).
Click here to see the generated report.
Now you see the excelReport Generated. Its so simple huh !!!

*If you see the columns in the excel were disturbed please change the settings or Use the latest Version. I have made this using  ‘Libre’.