Skip to content

tests.LoginTest need to share an instance of WebDriver with utils.listener.TestListener; an possible alternative implementation using ITestContext#12

Open
kazurayam wants to merge 1 commit intoswtestacademy:masterfrom
kazurayam:master
Open

tests.LoginTest need to share an instance of WebDriver with utils.listener.TestListener; an possible alternative implementation using ITestContext#12
kazurayam wants to merge 1 commit intoswtestacademy:masterfrom
kazurayam:master

Conversation

@kazurayam
Copy link

@kazurayam kazurayam commented Apr 21, 2024

Thank you for your great article https://www.swtestacademy.com/extent-reports-in-selenium-with-testng/ It helped me a lot. Let me post my small pull request.

utils.listener.TestListner#onTestFailure() is designed to take a screenshot of the browser on a failure detected by the @Test-annotated method of tests.LoginTest. TestListener need to have a reference to the instance of WebDriver which was created by the LoginTest class.

Here is a technical issue. The Test class creates a WebDriver instance; The Test Listener need a reference to the WebDriver instance. How to share the WebDriver instance between the two?

There could be multiple design options. The original utils.listener.TestListner#onTestFailure() gets access to the WebDriver instance by the following 2 lines of code:

    @Override
    public void onTestFailure(ITestResult iTestResult) {
        ...
        Object testClass = iTestResult.getInstance();
        WebDriver driver = ((BaseTest) testClass).getDriver();

OK. This certainly works. However I find two issues in the original code.

Issue1 : utils.listener.TestListener extends tests.BaseTest, which is unnecessary

I think that the author possibly forgot to erase the inheritance.

Issue2 : Should use ITestContext

we should rather use TestNG ITestContextto share the WebDriver instance between the Test class and the TestListener. For example, the test.BaseTest should say

public class BaseTet {
    ...
    private WebDriver driver;
    ...
    @BeforeClass
    public void classLevelSetup(ITestContext context) {
        ....
        context.setAttribute("WebDriver", driver)
        }

}

The following article told me of the coding gotcha.

Is there any official documentation that describes that we can write ITestContext object as a prameter for @BeforeXXX-annotated method? ... Yes. See the following.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant