写在前面

官方给的栗子是Junit,但是我仍是用TestNG来进行脚本的编写,这里只分享思路,不管是哪个测验框架基本思路都是相同的,喜爱用官方的Junit的,建议查看官方文档

如何编写测验脚本

在@BeforeClass方法中初始化Playwright和Browser并在@AfterClass中销毁它们,详细示例如下:

import com.microsoft.playwright.*;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
 * 用例编写
 */
public class TestExample {
    static Playwright playwright;
    static Browser browser;
    static BrowserContext context;
    static Page page;
    @BeforeClass
    static void launchBrowser() {
        playwright = Playwright.create();
        browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setArgs(Collections.singletonList("--start-maximized"))
                .setHeadless(false).setSlowMo(5000));
        context = browser.newContext(new Browser.NewContextOptions()
                .setViewportSize(1920, 1080));
        page = context.newPage();
    }
    @Test
    public void shouldSearchSoftTest() throws InterruptedException {
        page.navigate("https://www.baidu.com/");
        page.locator("#kw").fill("公众号:软件测验君");
        page.locator("#kw").press("Enter");
        String value = page.getAttribute("#kw", "value");
        Assert.assertEquals(value, "公众号:软件测验君");
        System.out.println(page.url());
    }
    @AfterClass
    public void afterClass() {
        browser.close();
        context.close();
        playwright.close();
    }
}

写在最终

至于测验用例的串联、执行、陈述展现方面,个人仍是喜爱TestNg,喜爱JUnit的同学可以参考Junit5。