All IT Courses 50% Off
Selenium Tutorials

PDF Report Generation in Selenium Using TestNG and ITextPDF

We all know that in testing presentation matters every time, so, it is always a good job to present a well-elaborated test report s. We already have discussed different techniques of test report generation in selenium and logging with ITestListener, and WebDriverListener. All these techniques are the way to represent test execution in an elaborated manner. Today in this article we will learn how to report a test in PDF report of the entire test execution.

To report a test in PDF format we use iText JAR file and we will further integrate it with TestNG reporting. Hence, we will use iText PDF with TestNG’s IReporter Listener.

Pre-requisites for PDF report generation in selenium

There are some pre-requisites to generate PDF report in Selenium. Those pre-requisites are listed below:

  1. Your project should be configured with iText Java API. To download the iText API go to the site https://sourceforge.net/projects/itext/  and click on the Download button. Once you have downloaded the JAR file, we need to add it to your project as we add external JAR files in Selenium.
itext.PNG

If you are using Maven, then you can create dependencies for the iText JAR file. To get the maven dependencies to go to the link https://mvnrepository.com/artifact/com.itextpdf/itextpdf, and click PDF Libraries under the Categories section.

Java Definition of Itext Declaration to Write to the Pdf File

String fileName = "filename.pdf";
FileOutputStream fos = new FileOutputStream(fileName);
Document docu = new Document();
PdfWriter.getInstance(docu, fos);
doc.open();
doc.addAuthor("authorName");
doc.addTitle("title");
doc.addSubject("description");
doc.add(new Paragraph("This is a paragraph"));
doc.close();

Code Explanation

Here initially we will create the String definition of the path of the PDF file. Then, the instance of the Document class creates a new PDF file. Further, the PdfWriter.getInstance method is used to give the path of the file and open() and close() methods are used to open and close the file respectively. By using open and close, we will declare Author Name, Title, Subject, and PDF report with addAuthor, addTitile, addSubject, and add(new Paragraph()) methods respectively.

All IT Courses 50% Off

Steps to Generate Pdf Report in Selenium

Below are the steps to generate a PDF report with our test execution data.

Step 1: to Define Pdf Actions Create a Separate Class

Here in this step we will create a separate class in which we have created a separate method for each action.

package Test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
public class CreatePDFReport {
Document docu;
public void openPdfPath() throws FileNotFoundException, DocumentException{
String fileName
 = new File("").getAbsoluteFile().toString()+"/TestReport/pdf-"+System.currentTimeMillis()+".pdf";
FileOutputStream fos = new FileOutputStream(fileName);
docu = new Document();
PdfWriter.getInstance(docu, fos);
docu.open();
}
public void addData(String authorName, String title, String description){
docu.addAuthor(authorName);
docu.addTitle(title);
docu.addSubject(description);
}
public void addParagraph(String text) throws DocumentException{
docu.add(new Paragraph(text));
}
public void closePdf(){
docu.close();
}
}

Step 2: Implement IReporter and Merge With Create pdf report.java Methods

Now we will implement IReporter for test reporting and add the data to the PDF file by extending CreatePDFReport.java.

seleniumpdfreportwithireporter.java

package Test;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.testng.IReporter;
import org.testng.IResultMap;
import org.testng.ISuite;
import org.testng.ISuiteResult;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.xml.XmlSuite;
public class SeleniumPDFReportWithIReporter extends CreatePDFReport implements IReporter{
@Override
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
for(ISuite ist : suites){
try{

openPdfPath();
//*************//
Map<String, ISuiteResult> resultSuiteMap = ist.getResults();
Set<String> key = resultSuiteMap.keySet();
for(String k : key){
ITestContext context = resultSuiteMap.get(k).getTestContext();
System.out.println("Suite Name- "+context.getName()
+"\n Report output Directory- "+context.getOutputDirectory()
+"\n Suite Name- "+context.getSuite().getName()
+ "\n Start Date Time for Execution- "+context.getStartDate()
+ "\n End Date Time for Execution- "+context.getEndDate());

addParagraph("Suite Name- "+context.getName()
+"\n Report output Directory- "+context.getOutputDirectory()
+"\n Suite Name- "+context.getSuite().getName()
+ "\n Start Date Time for Execution- "+context.getStartDate()
+ "\n End Date Time for Execution- "+context.getEndDate());
IResultMap resultMap  = context.getFailedTests();
Collection<ITestNGMethod> failedMethods = resultMap.getAllMethods();
System.out.println("------Failed Test Case-----");
for(ITestNGMethod imd : failedMethods){
System.out.println("Test Case Name- "+imd.getMethodName()
+"\n Description- "+imd.getDescription()
+"\n Priority- "+imd.getPriority()
+ "\n Date- "+new Date(imd.getDate()));

addParagraph("Test Case Name- "+imd.getMethodName()
+"\n Description- "+imd.getDescription()
+"\n Priority- "+imd.getPriority()
+ "\n Date- "+new Date(imd.getDate()));
}
IResultMap passedTest = context.getPassedTests();
Collection<ITestNGMethod> passedMethods = passedTest.getAllMethods();
System.out.println("------Passed Test Case-----");
for(ITestNGMethod imd1 : passedMethods){
System.out.println("Test Case Name- "+imd1.getMethodName()
+"\n Description- "+imd1.getDescription()
+"\n Priority- "+imd1.getPriority()
+ "\n Date- "+new Date(imd1.getDate()));

addParagraph("Test Case Name- "+imd1.getMethodName()
+"\n Description- "+imd1.getDescription()
+"\n Priority- "+imd1.getPriority()
+ "\n Date- "+new Date(imd1.getDate()));
}
}
//Closing PDF file
closePdf();
}catch (Exception e){
e.printStackTrace();
}
}
}
}

Step 3: Creating Testng Tests to Validate the Pdf Report

Below program contains two scenarios, in which, the first scenario fails the test and second scenario will pass the test. Further, reporting will be printed in PDF, Custom TestNG report and console as well.

mysampletestpdffile.java

package Test;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class TestPDFFile {
WebDriver driver;
@BeforeClass
public void setUp(){
System.setProperty("webdriver.chrome.driver", "src\\main\\java\\com\\browserdrivers\\chromedriver.exe");
driver  = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://www.google.com/");
driver.manage().window().maximize();
}
@AfterClass
public void tearDown(){
driver.close();
driver.quit();
}
@Test(priority=1, description="Sample Test Fail Reported in PDF")
public void testMethod1() {
String expectedTitle = "TestingFailed";
Assert.assertEquals(driver.getTitle(), expectedTitle, "Title not matched"); 
}
@Test(priority=0, description="Sample Test Pass Reported in PDF")
public void testMethod2() {
boolean matchCondition = driver.getTitle().contains("Google");
Assert.assertTrue(matchCondition, "Title matched");
}

}

Step 4:

Testng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Sample Test Suite">
<listeners>
<listener class-name="Test.SeleniumPDFReportWithIReporter"/>
<listener class-name="Test.ListenersDefinitionClass"/>
</listeners>
<!-- Test -->
<test name="Google Test" >
<classes>
<class name="Test.TestPDFFile"/>
</classes>
</test> 
<!-- End Test -->
</suite> <!-- Suite -->

Step 5: Execute the testng.xml file and refresh the project. You could see your project as below image.

Expand ‘TestReport’ folder and you should find a pdf which is the default report generated by TestNG.

pdf.PNG

Double-click on pdf file to open the file.

Conclusion:

  • To customize the TestNG report we need to implement by using two interfaces, ITestListener and IReporter.
  • We need ITestListener, if we want to get a report between execution, 
  • We need to implement IReporter, for creating a final report once after execution completes.
  • To generate pdf reports we need to add IText jar file in the project.
selenium automation
Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Back to top button