In this blog we will be utilizing Playwright Java to create a TestNg Test.
Topics that we will cover:
- Add TestNG maven dependency
- Create TestNG test
- Source code
Add TestNG maven dependency
We start by adding TestNg dependency in pom.xml
Navigate to below site

Paste in pom.xml file

Note: The dependency (see below) shows the scope as ‘test’. This means, the TestNg jar will only be recognized under src/test/java folder

Thus TestNg jar will not be recognized under src/main/java folder. If TestNg jar needs to be recognized under src/main/java folder, simply remove test scope from dependency. As of now, let us leave the scope as is.
Create TestNG Test
We will now create TestNg test utilizing the TestNg jar library.
Let us create a class under under src/test/java and create 3 annotations:
@BeforeMethod, @Test, @AfterMethod
We will also create 3 methods: setUp(), test_1(), tearDown()

We would initialize playwright instance, browser and page instance etc inside @BeforeMethod

We will write our actual Test within @Test

The error is thrown because the ‘page’ object created under @BeforeMethod is local to @BeforeMethod. Hence @Test method does not recognize ‘page’ object created inside @BeforeMethod.
We will create instance variables to correct the error. These variables can be accessed throught entire class

@Test does not throw any error now

Our code looks like below:

Notice that the desired text gets typed inside the frame

This is how we can create and execute a TestNG test using playwright java.
Source code
package com.rsa.playwrightjava;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Locator;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
public class Blog28_TestNGTest_PWJava {
private Browser browser;
private Page page;
@BeforeMethod
public void setUp() {
Playwright playwright = Playwright.create();
browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
page = browser.newPage();
}
@Test
public void test_1() {
page.navigate("https://the-internet.herokuapp.com/iframe");
Locator frame1 = page.frameLocator("#mce_0_ifr").locator("html");
frame1.click();
frame1.type("https://rahulshettyacademy.com");
}
@AfterMethod
public void tearDown() {
page.pause();
browser.close();
page.close();
}
}
Thanks.