I'm developing a wrapper Framework for Playwright Java and I have my custom wrapper class which creates a page , and also I have my custom listener class which takes screenshot on failure , now I want to add the page that gets created to ItestResult Attributes , but Im running into a null pointer
Below is a sample test class method
@BeforeClass(alwaysRun = true)
public void setUp(ITestContext iTestContext) throws InterruptedException {
page = getPage("Default");
}
@Test(priority = 0, description = "Verify Navigation to Application successfully")
public void navDishLandPage1() throws InterruptedException {
page.goTo("https://mvnrepository.com/artifact/com.microsoft.playwright/playwright/1.31.0");
Assert.assertEquals(page.getTitle(), "TTT");
}
Below is my wrapper Method to create a page
Page scrnShtPg; //used to store the page getting created
public BaseBrowser retrievePage(Browser browser, ThreadLocalContextMap contextMap, BrowserContext browserContext, String contextKey) {
if (contextMap.containsKey(contextKey)) {
browserContext = contextMap.get(contextKey);
} else {
contextMap.put(contextKey, browser.newContext(new Browser.NewContextOptions().setIgnoreHTTPSErrors(true)));
browserContext = contextMap.get(contextKey);
}
//testing
scrnShtPg=browserContext.newPage();
ITestResult itr = Reporter.getCurrentTestResult();
itr.setAttribute("Page_Reference", scrnShtPg); //Feeding the page to ItestResult
//testing
return new BaseBrowser(scrnShtPg);
}
Below is my custom listener class to take screenshot
@Override
public void onTestFailure(ITestResult iTestResult) {
JsonObject element = null;
byte[] bufferImage=null;
Page page = (Page) iTestResult.getAttribute("Page_Reference"); //throws a null pointer exception
bufferImage = page.screenshot();
try {
element = SyscoLabReporting.getElement(iTestResult, bufferImage);
elements.add(element);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Expecting solution
I want to initialize my getPage(); outside of @Test , maybe in @BeforeTest , @BeforeClass and then to be accessible from my custom listener class to take screenshot
Note - If I use my getPage(); inside @Test it works without any issue
This problem was resolved by using ItestContext in the page creation method as below
and you can call the set value in your listener class by