写在前面
官方给的栗子是Junit,但是我还是用TestNG来进行脚本的编写,这里只分享思路,不管是哪个测试框架基本思路都是一样的,喜欢用官方的Junit的,建议查看官方文档。
如何编写测试脚本
在@BeforeClass方法中初始化Playwright和Browser并在@AfterClass中销毁它们,具体示例如下:
代码语言:javascript复制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。