PDF Report Generation in Selenium Using TestNG

Profile picture for user arilio666

In this article, we will be discussing how we can generate pdf reports using TestNG. For this, we will have to install a dependency called iText pdf.

<dependency>
   <groupId>com.itextpdf</groupId>
   <artifactId>itextpdf</artifactId>
   <version>5.5.13.3</version>
</dependency>
  • This will be integrated with TestNG, and a pdf report will be created.

iText Declaration Code:

String fileName = "filename.pdf";
FileOutputStream fos = new FileOutputStream(fileName);
Document doc = new Document();
PdfWriter.getInstance(doc, fos);
doc.open();
doc.addAuthor("authorName");
doc.addTitle("title");
doc.addSubject("description");
doc.add(new Paragraph("This is paragraph"));
doc.close();
  • This how the declaration of iText should look like.
  • Then we create an outputstream for the file to be saved.
  • Then we open the doc and add our custom titles and stuff.
  • At last, we close the doc.

1.) PDF Action Class.

  • Let us create a class separately for the pdf actions we discussed above.
package week4.day2;
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 PDFAction {
    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();
    }
}

2.) IReporter Implementation

  • Extend PDFAction with the Current new class and implement IReporter to complete integration.
package week4.day2;
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 PDFAction 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();
            }
        }
    }
}

3.) Test File

  • We will be running a testng file called popUp.
  • package week4.day2;
    import java.util.List;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.testng.annotations.Test;
    import io.github.bonigarcia.wdm.WebDriverManager;
    public class PopUp {
        @Test
        public void popUp() throws Throwable {
            WebDriverManager.chromedriver().setup();
            ChromeDriver driver = new ChromeDriver();
            driver.get("https://www.programsbuzz.com/");
            driver.manage().window().maximize();
            Thread.sleep(3000);
            List<WebElement> elementTexts = driver.findElements(By.xpath("//div[@class='header__main__left']"));
            for (WebElement webElement : elementTexts) {
                System.out.println(webElement.getText());
            }
        }
    }
  • Create a testng.xml on the project's root and add in the configurations.
<?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="week4.day2.SeleniumPDFReportWithIReporter"/>
</listeners>
<!-- Test -->
 <test name="PDF Test" >
   <classes>
     <class name="week4.day2.PopUp"/>
   </classes>
 </test> 
 <!-- End Test -->
 
</suite> <!-- Suite -->
  • When done, run the XML file using testng. This will trigger the classes and generate a pdf report.