π Self-Contained Reporting, Wire Payloads & Parallel Test Telemetry
While Allure provides interactive dashboards with CLI servers, many enterprise testing environments require completely standalone, single-file HTML reports that can be emailed directly to stakeholders, hosted on static S3 buckets, or archived as CI artifacts without running specialized CLI server daemons. ExtentReports 5.x (SparkReporter) offers an industry-standard visual reporting solution for Java test frameworks. However, in concurrent REST Assured execution suites, sharing an ExtentTest instance causes log collisions and mangled test timelines across worker threads. By encapsulating active tests in a ThreadLocal<ExtentTest> container, wiring test events through a customized TestNG ITestListener, and utilizing MarkupHelper.createCodeBlock() to format outbound request payloads and inbound JSON responses with syntax highlighting, automation architects deliver high-fidelity API execution dashboards with complete thread safety.
EXTENTREPORTS 5.x THREADLOCAL CONCURRENCY & EVENT LIFECYCLE:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SINGLETON EXTENTREPORTS ENGINE (Global Suite Lifecycle Scope) β
β ExtentSparkReporter spark = new ExtentSparkReporter("target/ExtentReports/ExtentReport.html") β
β ExtentReports extent = new ExtentReports(); extent.attachReporter(spark); β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (ITestListener onTestStart: Spawns ExtentTest)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ExtentTestManager: private static final ThreadLocal<ExtentTest> extentTestThreadLocal β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββ
βΌ βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
β WORKER THREAD-1 (Student Registration Test) β β WORKER THREAD-2 (Curriculum Catalog Test) β
ββββββββββββββββββββββββββββββββββββββββββββββββ€ ββββββββββββββββββββββββββββββββββββββββββββββββ€
β 1. extentTestThreadLocal.set(t1) β β 1. extentTestThreadLocal.set(t2) β
β 2. Dispatches POST /v1/students β β 2. Dispatches GET /v1/curriculum β
β 3. Logs Wire Request via MarkupHelper: β β 3. Logs Wire Request via MarkupHelper: β
β ExtentTestManager.logRequest(reqBody) β β ExtentTestManager.logRequest(queryParams) β
β 4. Logs Wire Response via MarkupHelper: β β 4. Logs Wire Response via MarkupHelper: β
β ExtentTestManager.logResponse(respJson) β β ExtentTestManager.logResponse(respJson) β
β 5. ITestListener onTestSuccess / onTestFail β β 5. ITestListener onTestSuccess / onTestFail β
ββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Suite Complete: ISuiteListener / onFinish)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β STANDALONE HTML REPORT COMPILATION: extent.flush() βββΊ target/ExtentReports/ExtentReport.html β
β βββ Executive Summary Dashboard: Pie charts, Pass/Fail metrics, category distributions β
β βββ Chronological Timeline: Execution steps, millisecond durations per API call β
β βββ Syntax-Highlighted Code Blocks: Outbound JSON request and inbound response payloads β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
extentreports with modern Spark reporting capabilities, avoiding legacy version conflicts with third-party libraries.
<!-- ==============================================================================
MAVEN POM.XML: EXTENTREPORTS 5.x DEPENDENCIES
============================================================================== -->
<properties>
<extentreports.version>5.1.1</extentreports.version>
<testng.version>7.9.0</testng.version>
<restassured.version>5.4.0</restassured.version>
</properties>
<dependencies>
<!-- ExtentReports 5.x Core & SparkReporter Engine -->
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>${extentreports.version}</version>
</dependency>
<!-- REST Assured Core Dependency -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>${restassured.version}</version>
<scope>test</scope>
</dependency>
<!-- TestNG Testing Framework -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
ExtentManager to initialize the HTML SparkReporter, and ExtentTestManager using ThreadLocal<ExtentTest> to manage concurrent test threads.
package com.nikita.restassured.reports.extent;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
import com.aventstack.extentreports.reporter.configuration.Theme;
import java.io.File;
// ==============================================================================
// 1. GLOBAL EXTENTREPORTS SINGLETON ENGINE
// ==============================================================================
public class ExtentManager {
private static ExtentReports extent;
private static final String REPORT_PATH = "target/ExtentReports/ExtentReport.html";
public static synchronized ExtentReports getInstance() {
if (extent == null) {
new File("target/ExtentReports").mkdirs();
ExtentSparkReporter spark = new ExtentSparkReporter(REPORT_PATH);
// Configure dashboard presentation and visual theme
spark.config().setTheme(Theme.STANDARD);
spark.config().setDocumentTitle("REST Assured API Automation Dashboard");
spark.config().setReportName("Enterprise Microservices Regression Suite");
spark.config().setTimeStampFormat("MMM dd, yyyy HH:mm:ss");
extent = new ExtentReports();
extent.attachReporter(spark);
// Inject global environment metadata into report dashboard
extent.setSystemInfo("Target Stage", System.getProperty("env", "staging").toUpperCase());
extent.setSystemInfo("Base URL", "https://staging-api.nikita-infotech.com/v1");
extent.setSystemInfo("Java Runtime", System.getProperty("java.version"));
extent.setSystemInfo("Execution Engine", "REST Assured + TestNG Parallel");
extent.setSystemInfo("Author", "Nikita Sharma");
System.out.println("[*] ExtentManager initialized: Output bound to " + REPORT_PATH);
}
return extent;
}
}
// ==============================================================================
// 2. THREAD-LOCAL TEST INSTANCE MANAGER
// ==============================================================================
class ExtentTestManager {
private static final ThreadLocal<ExtentTest> testThreadLocal = new ThreadLocal<>();
public static ExtentTest getTest() {
return testThreadLocal.get();
}
public static void setTest(ExtentTest test) {
testThreadLocal.set(test);
}
public static void removeTest() {
testThreadLocal.remove();
}
}
ITestListener to automatically spawn tests on start, log pass/fail statuses, record throwables on failures, flush reports on completion, and clean up thread memory.
package com.nikita.restassured.reports.extent;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
public class ExtentTestNgListener implements ITestListener {
private static final ExtentReports extent = ExtentManager.getInstance();
@Override
public void onTestStart(ITestResult result) {
String testName = result.getMethod().getMethodName();
String description = result.getMethod().getDescription();
// Spawn test under thread-isolated storage
ExtentTest test = extent.createTest(testName, description);
ExtentTestManager.setTest(test);
// Assign category groups if specified on test
String[] groups = result.getMethod().getGroups();
for (String group : groups) {
test.assignCategory(group);
}
test.log(Status.INFO, "Started execution of test: " + testName);
}
@Override
public void onTestSuccess(ITestResult result) {
ExtentTest test = ExtentTestManager.getTest();
if (test != null) {
test.log(Status.PASS, MarkupHelper.createLabel("TEST PASSED: " + result.getName(), ExtentColor.GREEN));
}
ExtentTestManager.removeTest();
}
@Override
public void onTestFailure(ITestResult result) {
ExtentTest test = ExtentTestManager.getTest();
if (test != null) {
test.log(Status.FAIL, MarkupHelper.createLabel("TEST FAILED: " + result.getName(), ExtentColor.RED));
// Log root-cause exception stack trace directly to report
test.fail(result.getThrowable());
}
ExtentTestManager.removeTest();
}
@Override
public void onTestSkipped(ITestResult result) {
ExtentTest test = ExtentTestManager.getTest();
if (test != null) {
test.log(Status.SKIP, MarkupHelper.createLabel("TEST SKIPPED: " + result.getName(), ExtentColor.ORANGE));
}
ExtentTestManager.removeTest();
}
@Override
public void onFinish(ITestContext context) {
// Crucial: Flushes all buffered test logs to physical HTML file on disk
if (extent != null) {
extent.flush();
System.out.println("[*] ExtentReports: Flushed test execution dashboard to disk.");
}
}
}
MarkupHelper.createCodeBlock(payload, CodeLanguage.JSON) to display formatted, syntax-highlighted request and response bodies in the HTML report.
package com.nikita.restassured.reports.extent;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.CodeLanguage;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import io.restassured.response.Response;
import java.util.Map;
public class ExtentReportUtils {
/**
* Logs outgoing HTTP request details with code-block formatting
*/
public static void logRequestDetails(String method, String endpoint, String jsonBody, Map<String, String> headers) {
ExtentTest test = ExtentTestManager.getTest();
if (test == null) return;
test.log(Status.INFO, MarkupHelper.createLabel("HTTP METHOD: " + method + " | URL: " + endpoint, ExtentColor.BLUE));
if (headers != null && !headers.isEmpty()) {
String[][] headerMatrix = headers.entrySet().stream()
.map(e -> new String[]{e.getKey(), e.getValue()})
.toArray(String[][]::new);
test.info(MarkupHelper.createTable(headerMatrix));
}
if (jsonBody != null && !jsonBody.trim().isEmpty()) {
test.info("Outbound Request Payload:");
test.info(MarkupHelper.createCodeBlock(jsonBody, CodeLanguage.JSON));
}
}
/**
* Logs incoming HTTP response details with status badges and code-block formatting
*/
public static void logResponseDetails(Response response) {
ExtentTest test = ExtentTestManager.getTest();
if (test == null) return;
int statusCode = response.getStatusCode();
ExtentColor badgeColor = (statusCode >= 200 && statusCode < 300) ? ExtentColor.GREEN : ExtentColor.RED;
test.log(Status.INFO, MarkupHelper.createLabel("RESPONSE STATUS: HTTP " + statusCode + " (" + response.getTime() + " ms)", badgeColor));
test.info("Inbound Response Body:");
test.info(MarkupHelper.createCodeBlock(response.getBody().asPrettyString(), CodeLanguage.JSON));
}
}
ExtentTestManager without adding manual logging statements in test methods.
package com.nikita.restassured.reports.extent;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.CodeLanguage;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
public class ExtentLoggingFilter implements Filter {
@Override
public Response filter(FilterableRequestSpecification requestSpec,
FilterableResponseSpecification responseSpec,
FilterContext ctx) {
ExtentTest test = ExtentTestManager.getTest();
// 1. Intercept and log request before network round-trip
if (test != null) {
test.log(Status.INFO, MarkupHelper.createLabel("REQUEST: " + requestSpec.getMethod() + " " + requestSpec.getURI(), ExtentColor.BLUE));
if (requestSpec.getBody() != null) {
test.info("Request Body:");
test.info(MarkupHelper.createCodeBlock(requestSpec.getBody().toString(), CodeLanguage.JSON));
}
}
// 2. Transmit call over network socket
Response response = ctx.next(requestSpec, responseSpec);
// 3. Intercept and log response upon return
if (test != null) {
ExtentColor statusColor = (response.getStatusCode() >= 200 && response.getStatusCode() < 300)
? ExtentColor.GREEN : ExtentColor.RED;
test.log(Status.INFO, MarkupHelper.createLabel("RESPONSE: HTTP " + response.getStatusCode()
+ " [Latency: " + response.getTime() + " ms]", statusColor));
if (response.getBody() != null && !response.getBody().asString().isEmpty()) {
test.info("Response Payload:");
test.info(MarkupHelper.createCodeBlock(response.getBody().asPrettyString(), CodeLanguage.JSON));
}
}
return response;
}
}
package com.nikita.restassured.reports.extent;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
// Register Extent TestNG listener for automatic reporting
@Listeners(ExtentTestNgListener.class)
public class ExtentReportedTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
private RequestSpecification spec;
@BeforeClass
public void setupSpecification() {
spec = new RequestSpecBuilder()
.setBaseUri(BASE_URI)
.setContentType(ContentType.JSON)
.setAccept(ContentType.JSON)
// Attach custom ExtentLoggingFilter for automatic wire capture:
.addFilter(new ExtentLoggingFilter())
.build();
}
@Test(description = "Verify successful student registration with automatic ExtentReports payload logging",
groups = {"Smoke", "Regression"})
public void testStudentRegistrationExtentLogging() {
Map<String, Object> payload = new HashMap<>();
payload.put("studentId", "STU-88219");
payload.put("fullName", "Nikita Sharma");
payload.put("academicTrack", "ENTERPRISE_AUTOMATION");
payload.put("enrolledCredits", 16);
given()
.spec(spec)
.body(payload)
.when()
.post("/students")
.then()
.statusCode(201)
.body("status", equalTo("SUCCESS"))
.body("data.id", equalTo("STU-88219"));
System.out.println("[β] Registration verified. ExtentReports captured wire traffic automatically.");
}
@Test(description = "Verify negative boundary validation is documented with Extent failure labels",
groups = {"Regression"})
public void testNegativeBoundaryCredits() {
Map<String, Object> invalidPayload = new HashMap<>();
invalidPayload.put("studentId", "STU-88220");
invalidPayload.put("enrolledCredits", 0); // 0 credits triggers validation failure
given()
.spec(spec)
.body(invalidPayload)
.when()
.post("/students")
.then()
.statusCode(422)
.body("error", equalTo("CREDITS_BELOW_MINIMUM"));
System.out.println("[β] Negative boundary condition logged to Extent report.");
}
}
parallel="methods") and executing tests concurrently while confirming that test logs remain strictly isolated.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="ExtentParallelTestSuite" parallel="methods" thread-count="4" verbose="2">
<listeners>
<listener class-name="com.nikita.restassured.reports.extent.ExtentTestNgListener"/>
</listeners>
<test name="ExtentReportedTests" preserve-order="false">
<classes>
<class name="com.nikita.restassured.reports.extent.ExtentReportedTest"/>
</classes>
</test>
</suite>
NullPointerException on ExtentTestManager.getTest(), preventing overwritten logs in parallel suites, and resolving missing extent.flush() calls.
package com.nikita.restassured.reports.extent;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ExtentTriageTest {
// ==========================================================================
// PITFALL 1: NullPointerException ON ExtentTestManager.getTest()
// Symptom: Calling ExtentTestManager.getTest().info(...) throws NullPointerException!
//
// CAUSE: The test class did not register ExtentTestNgListener!
// As a result, onTestStart() never fired, leaving the ThreadLocal empty.
//
// FIX: Always register the listener via @Listeners(ExtentTestNgListener.class)
// or globally inside the testng.xml tag!
// ==========================================================================
@Test(description = "Verify defensive null handling prevents NPE when listener is missing")
public void testDefensiveNullCheck() {
// Defensive check pattern:
var test = ExtentTestManager.getTest();
if (test != null) {
test.info("Safe log message");
} else {
System.out.println("[*] Defensive Guard: ExtentTest is null for this thread (Listener not attached). Skipped log.");
}
Assert.assertTrue(true);
}
// ==========================================================================
// PITFALL 2: EMPTY REPORT FILE (0 BYTES) AFTER TEST EXECUTION
// Symptom: target/ExtentReports/ExtentReport.html is completely empty or missing!
//
// CAUSE: extent.flush() was never called!
// ExtentReports buffers all logs in memory and writes to disk only when
// flush() is executed.
//
// FIX: Ensure onFinish() in ITestListener calls extent.flush() unconditionally!
// ==========================================================================
}
EXTENTREPORTS 5.x SPECIFICATION REFERENCE MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β EXTENT CONSTRUCT β SYNTAX / API METHOD β PARAMETER TYPE β PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β ExtentSparkReporter β new ExtentSparkReporter(path)β File Path String β Binds output HTML destination β
β ExtentReports Engine β extent.attachReporter(spark) β Reporter Instanceβ Core reporting engine instanceβ
β System Info Injection β extent.setSystemInfo(k, v) β String Key/Value β Displays environment metadata β
β ThreadLocal Container β ThreadLocal<ExtentTest> β ExtentTest Objectβ Isolates logs per test thread β
β createTest β extent.createTest(name, desc)β String, String β Spawns individual test entry β
β assignCategory β test.assignCategory("Smoke") β String Category β Tags tests for group filteringβ
β Markup CodeBlock β MarkupHelper.createCodeBlock β JSON / XML Stringβ Pretty-prints wire payloads β
β Markup Label β MarkupHelper.createLabel(..) β String, Color β Badges status codes / results β
β Markup Table β MarkupHelper.createTable(m) β String[][] Matrixβ Formats request/resp headers β
β Throwable Logging β test.fail(throwable) β Throwable Object β Embeds exception stack traces β
β Filter Interceptor β ExtentLoggingFilter β REST Assured Fltrβ Automatically logs wire trafficβ
β Flush Engine β extent.flush() β Lifecycle Hook β Writes buffered logs to disk β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 EXTENTREPORTS BEST PRACTICES: β
β 1. Always use ThreadLocal<ExtentTest>: Prevent log collisions during parallel TestNG executions. β
β 2. Embed payloads via MarkupHelper.createCodeBlock(): Keep JSON payloads syntax-highlighted in the UI. β
β 3. Always call extent.flush() in onFinish(): Ensure all buffered report data is written to disk. β
β 4. Attach ExtentLoggingFilter to RequestSpecBuilder: Log wire exchanges without cluttering tests. β
β 5. Populate extent.setSystemInfo(): Display target environment, base URL, and build number on the UI. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ