DEV Community

Cover image for How to use Extent Reports with TestNG in Selenium Java
Manul wickrmanayaka
Manul wickrmanayaka

Posted on • Updated on

How to use Extent Reports with TestNG in Selenium Java

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:

ExtentReports class

ExtentTest class
Enter fullscreen mode Exit fullscreen mode

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:

PASS
FAIL
SKIP
INFO
Enter fullscreen mode Exit fullscreen mode

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.

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>
Enter fullscreen mode Exit fullscreen mode

Copy the TestNG dependency and set it in the pom.xml file.

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>
Enter fullscreen mode Exit fullscreen mode

As well as set the WebDriver maven dependency for make our test simple.

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>
Enter fullscreen mode Exit fullscreen mode

This is the dependency we need to import libraries from Extent Reports.

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>
Enter fullscreen mode Exit fullscreen mode

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.

ExtentSparkReporter htmlReporter = new ExtentSparkReporter("extentReport.html");
Enter fullscreen mode Exit fullscreen mode

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.

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();
 }
}
Enter fullscreen mode Exit fullscreen mode

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.

extent.flush();
Enter fullscreen mode Exit fullscreen mode

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

now Right click on it and open in a browser.

Alt Text

Alt Text

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.

@BeforeSuite
public void setup(){
}
@Test
public void test(){
}
@AfterSuite
public void tearDown(){
}
Enter fullscreen mode Exit fullscreen mode

@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”

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();
}
}
Enter fullscreen mode Exit fullscreen mode

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

Alt Text

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

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

Top comments (2)

Collapse
 
anandbhagwat profile image
Anand Bhagwat

Hi Manul, Thanks for sharing this. I am exploring this. wanted to ask, any reason you used test.pass? because even if test faill it will show test pass in testng, Any better aapproach for making pass fail like using testng ITestListener for onSuccess and onFail method?
any better way you suggest

Collapse
 
mwickrmanayaka profile image
Manul wickrmanayaka

Hi Anand, Thank you for your feedback.
Yes it would be better to pass ExtentReports instance in TestNG ITestListener methods.
And you can also try Creating a class implementing "IReporter" listener which is defined in the testng.xml file.

Find the explanation below
stackoverflow.com/questions/583915...