Extent Report 3 Add Screenshot

nicholas

I"m trying to build selenium with extent report but i could not get the save screenshot function working because i cannot reference the WebDriver object in the ITestListener class. Below is my sample code:

Test Runner.java:

@Listeners({com.peterwkc.Listener.TestListener.class})
public class ChromeTestManager {

    private WebDriverManager webDriverManager = new WebDriverManager();
    private WebDriver driver;

    private LoginPages loginPages;
    private AdminPages adminPages;

    @BeforeClass
    //@Parameters({"browser"})
    public void setupTest(/*String browser*/) throws MalformedURLException {
        System.out.println("BeforeMethod is started. " + Thread.currentThread().getId());
        // Set & Get ThreadLocal Driver with Browser

        webDriverManager.createDriver("chrome");
        driver = webDriverManager.getDriver();

        // Pages Object Initialization
        loginPages = PageFactory.initElements(driver, LoginPages.class);
        logoutPages = PageFactory.initElements(driver, LogoutPages.class);
        adminPages = PageFactory.initElements(driver, AdminPages.class);
    }

    @DataProvider(name = "loginCredentials")
    public static Object[][] getLoginCredentials() {
        return new Object [][] {{ "Admin123", "admin123"  }, {"testUser", "test"}, {"test", "test"}};
    }

    @Test(groups= {"Login"}, description="Invalid Login", priority = 0, dataProvider = "loginCredentials", invocationCount = 3) 
    public void login_invalid(String username, String password) {
        loginPages.login_invalid(driver, username, password);
    }
}

TestListener.java public class TestListener implements ITestListener {

    //Extent Report Declarations
    private static ExtentReports extent = ExtentManager.createInstance();
    private static ThreadLocal<ExtentTest> test = new ThreadLocal<>();

    public TestListener() {
    }

@Override
    public synchronized void onTestFailure(ITestResult result) {
        System.out.println((result.getMethod().getMethodName() + " failed!"));
        test.get().fail("Exception Error : \n" + result.getThrowable());

        /*String feature = getClass().getName();
        String screenShot;
        try {
            screenShot = CaptureScreenshot.captureScreen(driver, CaptureScreenshot.generateFileName(feature));
            test.get().addScreenCaptureFromPath(screenShot);
            test.get().log(Status.FAIL, screenShot);
        } catch (IOException ex) {    
            LogManager.logger.log(Level.INFO, "Exception: " + ex.getMessage());
        }*/

    }
}

Questions:

  • How to pass the WebDriver object from TestRunner.java to TestListener class?

  • How to save screenshot in extent report 3?

  • Anything wrong with my code?

please help, thanks in advance!

dangi13

Below are the steps to do this :

1 : Passing WebDriver object to Listener class

First create below method in ChromeTestManager class or at any another location from where you can call it, here suppose that it is present in ChromeTestManager class:

public static ITestContext setContext(ITestContext iTestContext, WebDriver driver) {
        iTestContext.setAttribute("driver", driver);

        return iTestContext;
    }

It will set the driver object to the TestContext.

Now change your @BeforeClass setUp method to accept parameter ITestContext, below is the code :

public class ChromeTestManager {

        private WebDriverManager webDriverManager = new WebDriverManager();
        private WebDriver driver;

        private LoginPages loginPages;
        private AdminPages adminPages;

        private static ITestContext context;  // creating a ITestContext variable

        @BeforeClass
        //@Parameters({"browser"})
        public void setupTest(ITestContext iTestContext) throws MalformedURLException {
            System.out.println("BeforeMethod is started. " + Thread.currentThread().getId());
            // Set & Get ThreadLocal Driver with Browser

            webDriverManager.createDriver("chrome");
            driver = webDriverManager.getDriver(); 

            this.context = setContext(iTestContext, driver);  // setting the driver into context

            // Pages Object Initialization
            loginPages = PageFactory.initElements(driver, LoginPages.class);
            logoutPages = PageFactory.initElements(driver, LogoutPages.class);
            adminPages = PageFactory.initElements(driver, AdminPages.class);
        }

When you run this, it will run smoothly and will not produce an error (If you are thinking that how I will pass ITestcontext context, It is handled internally)

Now the driver has been added as an object to the ITestcontext ;

Now Accessing the driver in Listener :

@Override
    public synchronized void onTestFailure(ITestResult result) {
        WebDriver driver = (WebDriver) result.getTestContext().getAttribute("driver");  // here we are accessing the driver object that we added in Test class  

}

2. Saving ScreenShot in extent report 3 (I am using dependency 3.1.5 in maven)

@Override
    public synchronized void onTestFailure(ITestResult result) {
        System.out.println("!!!!!!!!!!!!!!!!!!!! Test Failed !!!!!!!!!!!!!!!!!!!!");

        WebDriver driver = (WebDriver) result.getTestContext().getAttribute("driver"); // accessing driver here
        String feature = getClass().getName();
        String screenShot;
        try {
            screenShot = CaptureScreenshot.captureScreen(driver, CaptureScreenshot.generateFileName(feature));
            test.addScreenCaptureFromPath(screenShotPath);  // I am assuming that the "screenShot" is fully qualified path with extension e.g "C:\Users\12345\Desktop\sfgfdh.PNG"
        } catch (IOException ex) {    
            LogManager.logger.log(Level.INFO, "Exception: " + ex.getMessage());
        }

    }

3. Is there anything wrong with your code ?

No

You just need driver in Listener class and while adding screenshot in extent report , make sure that the path to screenshot is correct and is fully qualified path with extension.

Please let me know if you face an issue in this.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to attach custom/existing screenshot in allure report?

Extent report is not working in Cucumber 4.7.1

Difference between Tests and Steps in testng extent report

ExtentReports - screenshot not in the report - broken image

Extent Report Issue Parallel testing

How to add a screenshot to allure report with python?

D3 zoom in on brush extent

openlayers 3 zoom to combined extent

reproject map extent in openlayers 3

Openlayer 3 - check if a feature is within bounds of extent

How to display test name under Extent Report instead of Method Name?

Not able to save screenshot in klov reporter. (Extent Reports)

Karate Extent Report integrtion

Unable to generate Extent Report in Selenium Java

How to capture all test cases in extent report?

Extent report is not giving proper report on parallel execution

How to generate extent report in karate framework?

Unable to generate the extent-report

Extent Report 4 not creating report

java.io.IOException: Media was not found error while attaching a screenshot to extent report

How to Customise the Extent Report by removing unwanted graphs and Extra space

Migrating from Extent Report 3.1.5 to 4.1.6 for Selenium

Cypress BDD html report with screenshot for failed step

d3 - required help in brush extent()

How to generate report (Extent Report) in Specflow Project

Extent report logs for Test Steps is not working

Generate extent report using "ITestListener" or "IReporter" listeners

Is Extent report version 5 now available or not?

Extent Report Spark Disregards Line Feed (New Line)

TOP Ranking

  1. 1

    What exactly is memory mapped io and port based io

  2. 2

    How i extract text from a model dialog in selenium?

  3. 3

    pump.io port in URL

  4. 4

    Selenium browsing with headless isn't working?

  5. 5

    change TabView indicator SwiftUI

  6. 6

    python requests How to send data to a website

  7. 7

    Kubernetes pods not starting, running behind a proxy

  8. 8

    Scaffold-DbContext returns System.ArgumentNullException: Parameter name: proposedIdentifier in EFCore 2.0 when trying to pluralize

  9. 9

    Java POI: How to find an Excel cell with a string value and get its position (row) to use that position to find another cell

  10. 10

    Creating interaction sessions based on timestamps in pandas

  11. 11

    Maven annotation processing processor not found

  12. 12

    Missing field when deserializing using Jackson (Polymorphic)

  13. 13

    Spring Data JPA repository methods don't recognize property names with underscores

  14. 14

    Get all Woocommerce products from current product category term Id in a WP_Query

  15. 15

    How to update if key exists - sequelize

  16. 16

    I got message for error_log file "The stream or file ".../laravel.log" could not be opened: failed to open stream: Permission denied"

  17. 17

    Servlet: HTTP Status 404 - Not Found

  18. 18

    Type 'Moment' is not assignable to type 'Date'. Property 'toDateString' is missing in type 'Moment'

  19. 19

    what is key in CTTelephonyNetworkInfo().serviceSubscriberCellularProviders and CTTelephonyNetworkInfo().serviceCurrentRadioAccessTechnology

  20. 20

    Laravel(ajax) 404 not found

  21. 21

    Error: Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters

HotTag

Archive