extentreports-testng-adapter
extentreports-testng-adapter copied to clipboard
Question: How to use ExtentTest.log() method in @Before and @After methods
Hi there,
I am trying to build an e2e test automation solution using TestNG, extentreports and this adapter. I like using the extentreports test logger in the test methods I am using like so:
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.service.ExtentTestManager;
import com.aventstack.extentreports.testng.listener.ExtentITestListenerClassAdapter;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
@Listeners({ExtentITestListenerClassAdapter.class})
public class ExampleTests {
@Test
void testSomething() {
performAction1();
performAction2();
}
private void performAction1() {
ExtentTestManager.getTest().log(Status.INFO, "performing action 1");
/* other code goes here */
}
private void performAction2() {
ExtentTestManager.getTest().log(Status.INFO, "performing action 2");
}
}
However, the problem comes if I want to use the performAction1() as a setup, like when it makes sense that all tests in the suite perform this action before the actual test starts:
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.service.ExtentTestManager;
import com.aventstack.extentreports.testng.listener.ExtentITestListenerClassAdapter;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
@Listeners({ExtentITestListenerClassAdapter.class})
public class ExampleTests {
@BeforeMethod
void setup() {
performAction1();
}
@Test
void testSomething() {
performAction2();
}
private void performAction1() {
ExtentTestManager.getTest().log(Status.INFO, "performing action 1");
}
private void performAction2() {
ExtentTestManager.getTest().log(Status.INFO, "performing action 2");
}
}
This will obviously fail, because ExtentTestManager.getTest()
will return null
when we are in the @Before method.
Is there a graceful way to include the ExtentTest.log()
method in @Before methods?
Alternatives I have considered:
-
I have already considered switching to
org.testng.Reporter.log()
together with theExtentIReporterSuiteClassListenerAdapter
listener. But then, the logs are not shown in the Test view (Spark Reporter), which I find a bit inconvenient when investigating the report. -
I have also tried cheating by extending the @Before method like so
@BeforeMethod
void setup(ITestResult result) {
ExtentTestManager.createMethod(result, true);
performAction1();
}
However, then testSomething will appear as two tests in the log