I am having some difficulty tweaking ExtentReports to provide the desired output.
I have a simple test framework with TestNG, using a TestBase class to do the heavy lifting to keep tests simple. I wish to implement ExtentReports in a simple fashion, using the TestNG ITestResult interface to report Pass, Fail and Unknown.
Here are example tests, 1 pass and 1 deliberate fail:
public class BBCTest extends TestBase{
#Test
public void bbcHomepagePass() throws MalformedURLException {
assertThat(driver.getTitle(), (equalTo("BBC - Home")));
}
#Test
public void bbcHomePageFail() throws MalformedURLException {
assertThat(driver.getTitle(), (equalTo("BBC - Fail")));
}
And here is the relevant section in TestBase:
public class TestBase implements Config {
protected WebDriver driver = null;
private Logger APPLICATION_LOGS = LoggerFactory.getLogger(getClass());
private static ExtentReports extent;
private static ExtentTest test;
private static ITestContext context;
private static String webSessionId;
#BeforeSuite
#Parameters({"env", "browser"})
public void beforeSuite(String env, String browser) {
String f = System.getProperty("user.dir") + "\\test-output\\FabrixExtentReport.html";
ExtentHtmlReporter h = new ExtentHtmlReporter(f);
extent = new ExtentReports();
extent.attachReporter(h);
extent.setSystemInfo("browser: ", browser);
extent.setSystemInfo("env: ", env);
}
#BeforeClass
#Parameters({"env", "browser", "login", "mode"})
public void initialiseTests(String env, String browser, String login, String mode) throws MalformedURLException {
EnvironmentConfiguration.populate(env);
WebDriverConfigBean webDriverConfig = aWebDriverConfig()
.withBrowser(browser)
.withDeploymentEnvironment(env)
.withSeleniumMode(mode);
driver = WebDriverManager.openBrowser(webDriverConfig, getClass());
String baseURL = EnvironmentConfiguration.getBaseURL();
String loginURL = EnvironmentConfiguration.getLoginURL();
APPLICATION_LOGS.debug("Will use baseURL " + baseURL);
switch (login) {
case "true":
visit(baseURL + loginURL);
break;
default:
visit(baseURL);
break;
}
driver.manage().deleteAllCookies();
}
#BeforeMethod
public final void beforeTests(Method method) throws InterruptedException {
test = extent.createTest(method.getName());
try {
waitForPageToLoad();
webSessionId = getWebSessionId();
} catch (NullPointerException e) {
APPLICATION_LOGS.error("could not get SessionID");
}
}
#AfterMethod
public void runAfterTest(ITestResult result) throws IOException {
switch (result.getStatus()) {
case ITestResult.FAILURE:
test.fail(result.getThrowable());
test.fail("Screenshot below: " + test.addScreenCaptureFromPath(takeScreenShot(result.getMethod().getMethodName())));
test.fail("WebSessionId: " + webSessionId);
break;
case ITestResult.SKIP:
test.skip(result.getThrowable());
break;
case ITestResult.SUCCESS:
test.pass("Passed");
break;
default:
break;
}
}
private String takeScreenShot(String methodName) {
String path = System.getProperty("user.dir") + "\\test-output\\" + methodName + ".jpg";
try {
File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotFile, new File(path));
} catch (Exception e) {
APPLICATION_LOGS.error("Could not write screenshot" + e);
}
return path;
}
#AfterClass
public void tearDown() {
driver.quit();
}
#AfterSuite()
public void afterSuite() {
extent.flush();
}
Here is the report:
The issues are:
The name of the failed test is not recorded at left hand menu
The screenshot is not displayed despite correctly being taken
It is reporting both a Pass and Unexpected for the passed test
Version 3.0
Most of code is provided by person created this library, i just modified to your needs.
public class TestBase {
private static ExtentReports extent;
private static ExtentTest test;
#BeforeSuite
public void runBeforeEverything() {
String f = System.getProperty("user.dir")+ "/test-output/MyExtentReport.html";
ExtentHtmlReporter h = new ExtentHtmlReporter(f);
extent = new ExtentReports();
extent.attachReporter(h);
}
#BeforeMethod
public void runBeforeTest(Method method) {
test = extent.createTest(method.getName());
}
#AfterMethod
public void runAfterTest(ITestResult result) {
switch (result.getStatus()) {
case ITestResult.FAILURE:
test.fail(result.getThrowable());
test.fail("Screenshot below: " + test.addScreenCaptureFromPath(takeScreenShot(result.getMethod().getMethodName())));
break;
case ITestResult.SKIP:
test.skip(result.getThrowable());
break;
case ITestResult.SUCCESS:
test.pass("Passed");
break;
default:
break;
}
extent.flush();
}
protected String takeScreenShot(String methodName) {
String path = "./screenshots/" + methodName + ".png";
try {
File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotFile, new File(path));
} catch (Exception e) {
APPLICATION_LOGS.error("Could not write screenshot" + e);
}
return path;
}
}
You need several changes to make. Instantiate the ExtentReport & add configuration information in any of the configuration methods except BeforeClass.
#BeforeTest
#Parameters({"env", "browser"})
public void initialiseTests(String env, String browser, String emulatorMode, String mode) {
EnvironmentConfiguration.populate(env);
WebDriverConfigBean webDriverConfig = aWebDriverConfig()
.withBrowser(browser)
.withDeploymentEnvironment(env)
.withSeleniumMode(mode);
driver = WebDriverManager.openBrowser(webDriverConfig, getClass());
APPLICATION_LOGS.debug("Will use baseURL " + EnvironmentConfiguration.getBaseURL());
try {
visit(EnvironmentConfiguration.getBaseURL());
} catch (MalformedURLException e) {
e.printStackTrace();
}
driver.manage().deleteAllCookies();
}
Initailize test = extent.startTest(testName); in the #BeforeMethod section.
#BeforeMethod
public void beforeM(Method m) {
test = extent.startTest(m.getName());
}
And, you may call extent.endTest(test); in the #AfterTest method.
#AfterTest
public void afterTests() {
extent.endTest(test);
extent.close();
}
}
And, to log your step info call test.log(LogStatus, "your info to show"); with appropirate status.
Related
#Aftertest
#AfterSuite
#AfterClass Nothing is helpful in my case when we talk about sending the latest reports in the email.
#AfterSuite
public void statusupdate() throws Exception
{
SendMail.execute();
}
This is what I am doing and every time I am getting an older version of my emailable-report.html as I am struggling with JAVA as well so hopefully someone can help me understanding what is wrong here. My assumption is I am sending the email before the fresh report is generated but have no clue what to do next. Thanks for the patience and your replies.
Best you can do is to help yourself with Listeners for reports, instead of an #afterXxxx method.
So you can do something like:
import org.testng.annotations.Listeners;
#Listeners(TestListener.class)
public class MyTestClass {
#Test
public void myTest {
doTest();
}
}
Where your Listener has your SendMail action in the onFinish method:
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
public class TestListener implements ITestListener {
#Override
public void onTestStart(ITestResult result) {
}
#Override
public void onTestSuccess(ITestResult result) {
}
#Override
public void onTestFailure(ITestResult result) {
}
#Override
public void onTestSkipped(ITestResult result) {
}
#Override
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
}
#Override
public void onStart(ITestContext context) {
}
#Override
public void onFinish(ITestContext context) {
SendMail.execute();
}
}
I hope this does what you need, if not let me know.
Finally I am able to get the latest .html report by implementing extent reports and TestNG listeners in my framework. I am using 7.0 TestNG and its limitation is that it does not update the emailable-report.html so to overcome this problem you will have to implement extent reports where you will always get the latest .html fancy report which you can send through email in onFinish method of your listener class. But before jumping in you have to understand listeners and extent reports rest is given below. Also thanks #rodrigo for giving me a direction :)
public class TestClass{
WebDriver driver=null;
public ExtentHtmlReporter htmlReporter;
public ExtentReports extent;
public ExtentTest test;
public static String getScreenshot(WebDriver driver, String screenshotName) throws IOException {
String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date(0));
TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
// after execution, you could see a folder "FailedTestsScreenshots" under src folder
String destination = System.getProperty("user.dir") + "/Screenshots/" + screenshotName + dateName + ".png";
File finalDestination = new File(destination);
FileUtils.copyFile(source, finalDestination);
return destination;
}
#BeforeTest()
#Parameters("browser")
public void setup(String browsername) {
if(browsername.equalsIgnoreCase("chrome"))
{
WebDriverManager.chromedriver().setup();
driver=new ChromeDriver();
}
else if(browsername.equalsIgnoreCase("firefox"))
{
WebDriverManager.firefoxdriver().setup();
driver=new FirefoxDriver();
}
htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir")+"\\test-output\\myReport.html");
htmlReporter.config().setDocumentTitle("Automation Report"); // Tile of report
htmlReporter.config().setReportName("Functional Testing"); // Name of the report
htmlReporter.config().setTheme(Theme.DARK);
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
// Passing General information
extent.setSystemInfo("Host name", "NerdBox");
extent.setSystemInfo("Environemnt", "QA");
extent.setSystemInfo("user", "AB");
}
#Test(priority=1,enabled=true)
public void SubmitQuestions() throws Exception {
driver.manage().window().maximize();
driver.get("https://com/questions");
driver.findElement(By.xpath("/html/body/div/div/div[3]/div/div/div[1]/div/div/div[2]/div")).click();
}
#AfterMethod(alwaysRun=true)
public void end(ITestResult result) throws IOException
{
test= extent.createTest("The Test is "+result.getName());
if (result.getStatus() == ITestResult.FAILURE) {
test.log(Status.FAIL, "TEST CASE FAILED IS " + result.getName()); // to add name in extent report
test.log(Status.FAIL, "TEST CASE FAILED IS " + result.getThrowable()); // to add error/exception in extent report
String screenshotPath = NerdboxJobSubmit.getScreenshot(driver, result.getName());
test.addScreenCaptureFromPath(screenshotPath);// adding screen shot
} else if (result.getStatus() == ITestResult.SKIP) {
test.log(Status.SKIP, "Test Case SKIPPED IS " + result.getName());
}
else if (result.getStatus() == ITestResult.SUCCESS) {
test.log(Status.PASS, "Test Case PASSED IS " + result.getName());
}
}
#AfterTest(alwaysRun=true)
public void flush() throws Exception
{
System.out.println("After test");
extent.flush();
driver.quit();
}
My issue is mainly to know how to populate TestRail results after Cucumber scenarios are run. I'm trying to have the results from my JUnit tests run set on an existing TestRail run. I have the APIClient and APIException as per this project. I then created this JUnit class also copying that same project. Not sure how to proceed now as first time using Cucumber and JUnit. Our project has also a Hooks class and a MainRunner if that helps?
public class Hooks {
public static WebDriver driver;
#Before
public void initializeTest() {
System.out.println("Testing whether it starts before every scenario");
driver = DriverFactory.startDriver();
}
}
import java.io.File;
#RunWith(Cucumber.class)
#CucumberOptions(
features = {"src/test/java/clinical_noting/feature_files/"},
glue = {"clinical_noting.steps", "clinical_noting.runner"},
monochrome = true,
tags = {"#current"},
plugin = {"pretty", "html:target/cucumber",
"json:target/cucumber.json",
"com.cucumber.listener.ExtentCucumberFormatter:target/cucumber-
reports/report.html"}
)
public class MainRunner {
#AfterClass
public static void writeExtentReport() {
Reporter.loadXMLConfig(new File(FileReaderManager.getInstance().getConfigReader().getReportConfigPath()))
;
}
}
Thanks for the help.
Update
Got TestRail to update when running the JUnit tests separately. Still not sure how to do it after the Cucumber scenario is run though? That's how it's working now:
public class JUnitProject {
private static APIClient client = null;
private static Long runId = 3491l;
private static String caseId = "";
private static int FAIL_STATE = 5;
private static int SUCCESS_STATE = 1;
private static String comment = "";
#Rule
public TestName testName = new TestName();
#BeforeClass
public static void setUp() {
//Login to API
client = testRailApiClient();
}
#Before
public void beforeTest() throws NoSuchMethodException {
Method m = JUnitProject.class.getMethod(testName.getMethodName());
if (m.isAnnotationPresent(TestRails.class)) {
TestRails ta = m.getAnnotation(TestRails.class);
caseId = ta.id();
}
}
#TestRails(id = "430605")
#Test
public void validLogin() {
comment = "another comment";
Assert.assertTrue(true);
}
#Rule
public final TestRule watchman = new TestWatcher() {
Map data = new HashMap();
#Override
public Statement apply(Statement base, Description description) {
return super.apply(base, description);
}
#Override
protected void succeeded(Description description) {
data.put("status_id", SUCCESS_STATE);
}
// This method gets invoked if the test fails for any reason:
#Override
protected void failed(Throwable e, Description description) {
data.put("status_id", FAIL_STATE);
}
// This method gets called when the test finishes, regardless of status
// If the test fails, this will be called after the method above
#Override
protected void finished(Description description) {
try {
data.put("comment", comment);
client.sendPost("add_result_for_case/" + runId + "/" + caseId, data);
} catch (IOException e) {
e.printStackTrace();
} catch (APIException e) {
e.printStackTrace();
}
};
};
}
And the annotation
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD) //on method level
public #interface TestRails {
String id() default "none";
}
Working now. Had to add the scenario param inside the before method and do the TestRail connection from there.
#regressionM1 #TestRails(430605)
Scenario: Verify the user can launch the application
Given I am on the "QA-M1" Clinical Noting application
Then I should be taken to the clinical noting page
And
public class Hooks {
private static APIClient client = null;
private static Long runId = 3491l;
private static String caseId = "";
private static int FAIL_STATE = 5;
private static int SUCCESS_STATE = 1;
private static String SUCCESS_COMMENT = "This test passed with Selenium";
private static String FAILED_COMMENT = "This test failed with Selenium";
#Rule
public TestName testName = new TestName();
public static WebDriver driver;
#Before
public void initializeTest() {
client = testRailApiClient();
System.out.println("Testing whether it starts before every scenario");
driver = DriverFactory.startDriver();
}
#After()
public void tearDown(Scenario scenario) {
String caseIdSplit = "";
for (String s : scenario.getSourceTagNames()) {
if (s.contains("TestRail")) {
caseIdSplit = s.substring(11, 17); // Hardcoded for now as all the ids have 6 characters
System.out.println("Testing whether the browser closes after every scenario" + caseIdSplit);
}
}
caseId = caseIdSplit;
Map data = new HashMap();
if (!scenario.isFailed()) {
data.put("status_id", SUCCESS_STATE);
data.put("comment", SUCCESS_COMMENT);
} else if (scenario.isFailed()) {
data.put("status_id", FAIL_STATE);
data.put("comment", SUCCESS_COMMENT);
}
try {
client.sendPost("add_result_for_case/" + runId + "/" + caseId, data);
} catch (IOException e) {
e.printStackTrace();
} catch (APIException e) {
e.printStackTrace();
}
}
}
Update
Wrote a post on this here
I am having an issue where if I run a test that has 6 steps, 3 pass, 1 fail, 2 skipped. It will always report as Passed in my extent reports. I am using Klov. Is it possible that I have not correctly configured the report? and if so does anyone have suggestions to fix this issue.
public class MyRunner {
#BeforeClass
public static void initialize(){
d = new Date();
ExtentProperties extentProperties = ExtentProperties.INSTANCE;
extentProperties.setKlovServerUrl("http://localhost");
extentProperties.setKlovProjectName("Test Project");
extentProperties.setKlovReportName("Test Report: " + d);
extentProperties.setMongodbHost("localhost");
extentProperties.setMongodbPort(27017);
extentProperties.setMongodbDatabase("klov");
}
}
#AfterClass
public static void teardown(ITestResult result){
extent.flush();
}
}
And here is my test, it is just a simple test that opens googles login page, just to make sure the extent reports will do everything I need it to
public class Google {
WebDriver driver;
#Given("^that I am on the webpage Google$")
public void thatIAmOnTheWebpageGoogle() throws Throwable {
System.setProperty("webdriver.chrome.driver","\\\\hiscox.nonprod\\profiles\\Citrix\\XDRedirect\\CaseyG\\Desktop\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("https://accounts.google.com/signin/v2/identifier?hl=en&passive=true&continue=https%3A%2F%2Fwww.google.com%2F&flowName=GlifWebSignIn&flowEntry=ServiceLogin");
driver.manage().window().maximize();
MyRunner.logger.log(Status.INFO, "Opened Google login page")
//throw new PendingException();
//extent.createTest("Step 1").pass("log");
}
#When("^I try to login$")
public void i_try_to_login() throws Throwable {
// find the username field and enters the username, then clicks next
WebElement username = driver.findElement(By.xpath("//input[#id='identifierId']"));
username.sendKeys("********");
driver.findElement(By.id("identifierNext")).click();
//finds the password field and enters the password
WebElement password = driver.findElement(By.xpath("//input[#name='password']"));
password.sendKeys("**********");
Assert.assertFalse(true);
driver.findElement(By.id("passwordNext")).click();
//throw new PendingException();
//extent.createTest("Step 2").pass("log");
}
#Then("^I will be successfully logged into Google$")
public void i_will_be_successfully_logged_into_Google() throws Throwable {
String account = "Google Account: greg casey \n" + "(klovtest#gmail.com)";
//WebElement loggedInUser = driver.findElement(By.xpath("//*[#id="gbw"]/div/div/div[2]/div[4]/div[1]"))
//*[#id="gbw"]/div/div/div[2]/div[4]/div[1]/a
//extent.createTest("Step 3").pass("log");
throw new PendingException();
}
}
You should use ITestListener Interface on your Listener class where extent report's test is created
OnTestStart and do other things alos as descriobed below (I have used Thread for parallel device testing so you can ignore, rest is useful)
public class Listeners extends Utilities implements ITestListener {
ExtentReports extent = ExtentReporterTool.getReport();enter code here
ExtentTest test;
ThreadLocal<ExtentTest> testObjects = new ThreadLocal<ExtentTest>();
#Override
public void onTestStart(ITestResult result) {
test = extent.createTest(result.getMethod().getMethodName());
testObjects.set(test);
}
#Override
public void onTestSuccess(ITestResult result) {
testObjects.get().log(Status.PASS, "Test Case passed");
}
#Override
public void onTestFailure(ITestResult result) {
testObjects.get().fail(result.getThrowable());
WebDriver driver;
try {
driver = (WebDriver) result.getTestClass().getRealClass().getSuperclass().getField("driver")
.get(result.getInstance()); testObjects.get().addScreenCaptureFromPath(takeScreenshot(result.getMethod().getMethodName(), driver),
result.getMethod().getMethodName());
} catch (IOException | IllegalArgumentException | SecurityException | IllegalAccessException
| NoSuchFieldException e) {
e.printStackTrace();
}
}
#Override
public void onTestSkipped(ITestResult result) {
testObjects.get().log(Status.SKIP, "Test Case skipped");
}
#Override
public void onFinish(ITestContext context) {
extent.flush();
}
}
I'm trying to add Screenshots of the failed test case to the testNG report and I don't have any idea about it
This is my pom class for getting screenshot
package library;
import java.awt.AWTException;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
public class TakeScreenShot {
WebDriver driver;
public TakeScreenShot(WebDriver driver) {
this.driver=driver;
}
public void CaptureScreenshot(String screenshotName) throws AWTException
{
try {
TakesScreenshot ts=(TakesScreenshot)driver;
File source=ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, new File("C:\\Users\\Documents\\Eclipse\\WorkSpace\\ScreenShot\\"+screenshotName));
System.out.println("Screenshot taken");
} catch (Exception e) {
System.out.println("Exception "+e.getMessage());
}
}
}
And this is my TestNG class
#AfterMethod
public void CloseBrowser(ITestResult result) throws AWTException {
String name=result.getName()+"."+result.getMethod().getCurrentInvocationCount()+".png";
if(ITestResult.FAILURE==result.getStatus())
{
ScreenshotPageObjectModel screenshotPom= new ScreenshotPageObjectModel(driver);
screenshotPom.CaptureScreenshot(name);
}
driver.close();
}
Thanks for helping and please mention where should I do changes for adding the screenshot in the report
You need to use ITestListeners interface of TestNg, it basically provide 7 methods, those are :
onTestStart(ITestResult result)
onTestFailure(ITestResult result)
onTestSuccess(ITestResult result)
onTestSkipped(ITestResult result)
onTestFailedButWithinSuccessPercentage(ITestResult result)
onStart(ITestContext context)
onFinish(ITestContext context)
Your requirement here is "take screen shot of failed test cases/methods".You should use onTestFailure(ITestResult result) methods.
Demonstration :
public class TestListener implements ITestListener {
WebDriver driver=null;
String filePath = "D:\\SCREENSHOTS";
#Override
public void onTestFailure(ITestResult result) {
System.out.println("***** Error "+result.getName()+" test has failed *****");
String methodName=result.getName().toString().trim();
takeScreenShot(methodName);
}
public void takeScreenShot(String methodName) {
//get the driver
driver=TestBase.getDriver();
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//The below method will save the screen shot in d drive with test method name
try {
FileUtils.copyFile(scrFile, new File(filePath+methodName+".png"));
System.out.println("***Placed screen shot in "+filePath+" ***");
} catch (IOException e) {
e.printStackTrace();
}
}
public void onFinish(ITestContext context) {}
public void onTestStart(ITestResult result) { }
public void onTestSuccess(ITestResult result) { }
public void onTestSkipped(ITestResult result) { }
public void onTestFailedButWithinSuccessPercentage(ITestResult result) { }
public void onStart(ITestContext context) { }
}
You need to add this tag to your XML file:
<listeners>
<listener class-name="com.pack.listeners.TestListener"/>
</listeners>
To get screen shot use this method:
public static void takeSnapShot(WebDriver driver, String fileWithPath) throws Exception {
TakesScreenshot scrShot = (TakesScreenshot)driver;
File SrcFile = (File)scrShot.getScreenshotAs(OutputType.FILE);
File DestFile = new File(fileWithPath);
FileUtils.copyFile(SrcFile, DestFile);
}
You can call the screen shot under TestNG using below code:
#AfterMethod(
alwaysRun = true
)
protected void afterMethod(ITestResult result, Method method) throws Exception {
// boolean testStatus = false;
String fileName = "FAIL - Error Message Generated on Details Reports";
byte testStatus;
if (result.getStatus() == 2) {
fileName = System.getProperty("user.dir") + "\\Reports\\failure_screenshots\\" + ".png";
takeSnapShot(this.driver, fileName);
ExtentTestManager.getTest().log(LogStatus.FAIL, "Error Screenshot" + ExtentTestManager.getTest().addScreenCapture("failure_screenshots\\" + ".png"));
ExtentTestManager.getTest().log(LogStatus.FAIL, "Test Failed");
testStatus = 2;
} else {
ExtentTestManager.getTest().log(LogStatus.PASS, "Test passed");
testStatus = 1;
}
Ref-> https://www.softwaretestingmaterial.com/screenshots-extent-reports/
http://automationtesting.in/capture-screenshot-in-extent-reports-java/
Hope this helps!!!
PS- Use the most stable extent report version - 2.41.1
I suggest to use ReportNG instead of the TestNG premitive report.
Currently, I am using Selenium TestNG and Extent Reports framework for reporting. I am facing a problem where all are my test cases are showing Pass and not showing Fail.
#BeforeTest
public void setUp()
{
//where we need to generate the report
htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir")+"/test-output/MyReport.html");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
// Set our document title, theme etc..
htmlReporter.config().setDocumentTitle("My Test Report");
htmlReporter.config().setReportName("Test Report");
htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
htmlReporter.config().setTheme(Theme.DARK);
}
#Test
public void On_Page_IM() throws InterruptedException {
test = extent.createTest("On_Page_IM");
wd.manage().window().maximize();
Thread.sleep(10000);
test.log(Status.INFO,"On page intent media: Show");
}
#AfterSuite
public void tearDown()
{
extent.flush();
wd.quit();
}
After Added this code its solved
#AfterMethod
public void getResult(ITestResult result)
{
if(result.getStatus()==ITestResult.FAILURE)
{
test.log(Status.FAIL, result.getThrowable());
}
// extent.endTest(test);
}
Just add below code at end of ur tests
#AfterMethod
public void AfterMethod(ITestResult result) {
if (result.getStatus() == ITestResult.FAILURE) {
test.log(Status.FAIL,
MarkupHelper.createLabel(result.getName()
+ " Test case FAILED due to below issues:",
ExtentColor.RED));
test.fail(result.getThrowable());
} else if (result.getStatus() == ITestResult.SUCCESS) {
test.log(
Status.PASS,
MarkupHelper.createLabel(result.getName()
+ " Test Case PASSED", ExtentColor.GREEN));
} else {
test.log(
Status.SKIP,
MarkupHelper.createLabel(result.getName()
+ " Test Case SKIPPED", ExtentColor.ORANGE));
test.skip(result.getThrowable());
}
}
#AfterTest
public void AfterTest() {
extent.flush();
}
Selenium WebDriver 4 + JUnit 5 + Extent Reports 5 (JDK 17)
I used this and this to write the modern JUnit 5 solution, since most examples are for the older TestNG. ExtentHtmlReporter has also been deprecated.
abstract class BaseTest {
private static ExtentReports extent; // Prevent overwriting reports per test
protected WebDriver driver; // WebDriver should never be static
#RegisterExtension
protected AfterEachExtension afterEachExtension = new AfterEachExtension();
#BeforeAll
public static void beforeAll() {
extent = new ExtentReports();
spark = new ExtentSparkReporter("target/spark-reports/index.html");
extent.attachReporter(spark);
spark.config(
ExtentSparkReporterConfig.builder()
.theme(Theme.DARK)
.documentTitle("Extent Reports")
.build()
);
}
#BeforeEach
public void beforeEach() {
driver = // Initialise driver
}
#AfterEach
public void afterEach() {
AfterEachExtension.setExtent(extent);
afterEachExtension.setDriver(driver);
}
#AfterAll
public static void afterAll() {
extent.flush();
}
}
import com.aventstack.extentreports.Status;
// Other imports
public class AfterEachExtension implements AfterEachCallback {
private static ExtentReports extent;
private WebDriver driver;
public static void setExtent(ExtentReports extent) {
AfterEachExtension.extent = extent;
}
public void setDriver(WebDriver driver) {
this.driver = driver;
}
#Override
public void afterEach(ExtensionContext context) throws Exception {
var test = extent.createTest(context.getDisplayName());
context.getExecutionException().ifPresent(value -> test.log(Status.FAIL, value));
driver.quit();
}
}