How to use Extent Reports with TestNG in Selenium Java
Tags: automation, selenium, testng, extentreports
Published: 2021-05-22 16:30:06

###What are Extent Reports?

Extent Reports is an open-source HTML reporting library useful for test automation. It can be easily integrated with major testing frameworks like JUnit, NUnit, TestNG, etc. These reports are HTML documents that depict results as pie charts.

Extent Reports in Selenium contain two major, frequently used classes:
```javascript
ExtentReports class

ExtentTest class
``` 
Both classes can be used with the following built-in methods:

*startTest:** Executes preconditions of a test case
**endTest:** Executes postconditions of a test case
**Log:** Logs the status of each test step onto the HTML report being generated
**Flush:** Erases any previous data on a relevant report and creates a whole new report

A Test Status can be indicated by the following values:
```javascript
PASS
FAIL
SKIP
INFO
``` 
Lets get to know few methods of the above classes. First lets try to create a Project in Eclipse and apply it into a main method class then we can convert it into a TestNG Class.

OK, Now lets get started….

###1.Adding Dependencies to the pom.xml file

Create a maven project and lets name it as “TestNGextentReports”.
Since we are going to create a maven project lets get Extent Reports from the maven dependencies.

First copy the selenium dependency and set it in the pom.xml file.
```javascript
https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java/3.141.59
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.141.59</version>
</dependency>
```

Copy the TestNG dependency and set it in the pom.xml file.
```javascript
https://mvnrepository.com/artifact/org.testng/testng
<! —  https://mvnrepository.com/artifact/org.testng/testng →
<dependency>
 <groupId>org.testng</groupId>
 <artifactId>testng</artifactId>
 <version>7.4.0</version>
 <scope>test</scope>
</dependency>
``` 

As well as set the WebDriver maven dependency for make our test simple.
```javascript
https://mvnrepository.com/artifact/io.github.bonigarcia/webdrivermanager/4.4.3
<dependency>
    <groupId>io.github.bonigarcia</groupId>
    <artifactId>webdrivermanager</artifactId>
    <version>4.4.3</version>
</dependency>
```

This is the dependency we need to import libraries from Extent Reports.
```javascript
https://mvnrepository.com/artifact/com.relevantcodes/extentreports
<!-- https://mvnrepository.com/artifact/com.relevantcodes/extentreports -->
<dependency>
    <groupId>com.relevantcodes</groupId>
    <artifactId>extentreports</artifactId>
    <version>2.41.2</version>
</dependency>
```

###2.Create a Java class

Create a new class called “ExtentReport”. And include the main() method.

To create Extent Report references first you need to copy this statement to the main method.
```javascript
ExtentSparkReporter htmlReporter = new ExtentSparkReporter("extentReport.html");
``` 
We have now created a object called **“htmlReporter”** from the class **“ExtentSparkReporter”**. Here i gave the file name as **“extentReport.html”** so my results will be store there.

So after reference has set put this code in the class.
```javascript
package test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
import io.github.bonigarcia.wdm.WebDriverManager;
public class ExtentReport {
//creating driver object
 private static WebDriver driver = null;
 //setting expected title from the ebay.com
 static String expectedTitleebay ="Electronics, Cars, Fashion, Collectibles & More | eBay";
public static void main(String[] args) throws InterruptedException {
//create the htmlReporter object 
  ExtentSparkReporter htmlReporter = new ExtentSparkReporter("extentReport.html");
//create ExtentReports and attach reporter(s)
  ExtentReports extent = new ExtentReports();
  extent.attachReporter(htmlReporter);
//creates a toggle for the given test, add all log events under it
  ExtentTest test1 = extent.createTest("ebay Search Test", "test to validate search box ");
//initializing and starting the browser
  WebDriverManager.chromedriver().setup();
  driver = new ChromeDriver();
  test1.log(Status.INFO, "Starting test case");
//maximize the window 
  driver.manage().window().maximize();
  test1.pass("maximize has done");
//Navigate to Ebay.com
  driver.get("https://www.ebay.com");
  Thread.sleep(1000);
  test1.pass("Navigate to Ebay.com");
//compare whether the title id matching
  String actualTitle = driver.getTitle();
  Assert.assertEquals(actualTitle, expectedTitleebay);
  test1.pass("title is correct");
//enter in the TextBox
  driver.findElement(By.xpath("//*[@id=\"gh-ac\"]")).sendKeys("Mobile");
  test1.pass("Entered thex in the text box");
  //hit enter
  driver.findElement(By.xpath("//*[@id=\"gh-btn\"]")).sendKeys(Keys.RETURN); 
  test1.pass("Press keybopard enter key");
driver.close();
  test1.pass("closed the browser");
test1.info("test completed");
  //write results into the file
  extent.flush();
 }
}
``` 
So this code will go to **https://www.ebay.com**, validate the site by comparing Title and enter “mobile” in the search box and hit enter. 

Press **CTRL + SHIFT + O** to import all classes from the **avenstack** package.

You will find this method in above code.
```javascript
extent.flush();
``` 
Calling the **flush** method writes/updates the test information of your reporter to the destination type. otherwise if you do not use this you will not see any error in your program because you won’t get any report.

Now you have to refresh your Project and you will see **“extentReport.html”** file.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/imqp0yyv1ttwv43oiovi.png)

now Right click on it and open in a browser.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0p9241mrm0piq597fiwj.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/67v1mlhyx4d9de1eassh.png)

As you can see these are way better than TestNG Reports. It have very beautiful, clear and informative GUI. It also have two views which is very clear.

You can have the Time line graph, pass/fail rate, date/time and you will notice that it mentioned pass, info status clearly as we have given them in the code.

So this is how we create Extent Reports in selenium. Now lets try to apply the same test scenario to the TestNG class.

###3.Create a TestNG Class

Use the same package and create another class called **“ExtendReportTestNG”**.

Now create three functions as below. We are going to use TestNG annotations for these functions.
```javascript
@BeforeSuite
public void setup(){
}
@Test
public void test(){
}
@AfterSuite
public void tearDown(){
}
```
**@BeforeSuite** — In BeforeSuite I have initialized the ExtentSparkReporter and ChromeDriver

**@Test** — I have written the code to go to Daraz.lk and ebay.com and the Title will be checked with the actual title. Then it will insert “mobile” inside the textbox and hit enter.”

**@AfterSuite** — In here browser will be close and flush()

Copy this code to your project and run as a **“TestNG Test”**
```javascript
package test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
import io.github.bonigarcia.wdm.WebDriverManager;
public class ExtendReportTestNG {
//creating driver object
 private static WebDriver driver = null;
 //setting expected title from the ebay.com/Daraz.lk
 static String expectedTitleebay ="Electronics, Cars, Fashion, Collectibles & More | eBay";
 static String expectedTitledaraz ="Online Shopping Sri Lanka: Clothes, Electronics & Phones | Daraz.lk";
//create the htmlReporter object
ExtentSparkReporter htmlReporter;
 ExtentReports extent;
 ExtentTest test1,test2;
@BeforeSuite
 public void setup() {
htmlReporter = new ExtentSparkReporter("extentReport.html");
//create ExtentReports and attach reporter(s)
  extent = new ExtentReports();
  extent.attachReporter(htmlReporter);
  
  //initializing and starting the browser
  WebDriverManager.chromedriver().setup();
  driver = new ChromeDriver();
 
 }
@Test (priority = 1)
 public void test1() throws InterruptedException {
//creates a toggle for the given test, add all log events under it
  test1 = extent.createTest("ebay Search Test", "test to validate search box ");
test1.log(Status.INFO, "Starting test case");
  
  //maximize the window 
  driver.manage().window().maximize();
  test1.pass("maximize has done");
//Navigate to Ebay.com
  driver.get("https://www.ebay.com");
  Thread.sleep(1000);
  test1.pass("Navigate to Ebay.com");
//compare whether the title id matching
  String actualTitle = driver.getTitle();
  Assert.assertEquals(actualTitle, expectedTitleebay);
  test1.pass("title is correct");
//enter in the TextBox
  driver.findElement(By.xpath("//*[@id=\"gh-ac\"]")).sendKeys("Mobile");
  test1.pass("Entered text in the text box");
  //hit enter
  driver.findElement(By.xpath("//*[@id=\"gh-btn\"]")).sendKeys(Keys.RETURN); 
  test1.pass("Press keybopard enter key");
}
@Test (priority = 0)
 public void test2() throws InterruptedException {
//creates a toggle for the given test, add all log events under it
  test2 = extent.createTest("Daraz Search Test", "test to validate search box ");
test2.log(Status.INFO, "Starting test case");
//maximize the window 
  driver.manage().window().maximize();
  test2.pass("maximize has done");
  
  //Navigate to daraz.lk
  driver.get("https://www.daraz.lk/#");
  Thread.sleep(1000);
  test2.pass("Navigate to Daraz.lk");
//compare whether the title id matching
  String actualTitle = driver.getTitle();
  Assert.assertEquals(actualTitle, expectedTitledaraz);
  test2.pass("title is correct");
//enter in the TextBox
  driver.findElement(By.xpath("//*[@id=\"q\"]")).sendKeys("Mobile");
  test2.pass("Entered thex in the text box");
  //hit enter
  driver.findElement(By.xpath("//*[@id=\"topActionHeader\"]/div/div[2]/div/div[2]/form/div/div[2]/button")).sendKeys(Keys.RETURN); 
  test2.pass("Press keybopard enter key");
  
 }
 
 @AfterSuite
 public void tearDown() {
driver.quit();
test1.pass("closed the browser");
  test2.pass("closed the browser");
test1.info("test completed");
  test2.info("test completed");
  
  //write results into the file
  extent.flush();
}
}
``` 
I have used two **@Test** annotations to run two different sites separately. And have used prioritize method in each **@Test**

**priority = int** means that we can choose which **@Test** to run first and which one will run after that. It takes lowest number as the highest priority. And also it count minus numbers.

Ex: **priority = -1 > priority = 0** (-1 has higher priority than 0)

If we do not mentioned the priority it takes the alphabetical order of the method name.

Now lets have a look at the extent Reports.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/moflwv67c9ppesyomx3c.PNG)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ytdserip4qpvpfxa7tob.png)

As you can see in the left panel we can see both tests are categorized separately. We can go to each one and view the results.

So that’s it. This is how we use extent reports in our TestNG projects.

When we are dealing with bigger projects in selenium we can prioritize the tests, separate each one and have a clean code.

For your reference find my GitHub project [here](https://github.com/mwickramanayaka/Daraz-Add-to-card-test-Selenium.git) 
 

####𝑻𝑯𝑰𝑵𝑲 𝑸𝑼𝑨𝑳𝑰𝑻𝒀!