前言
我喜歡周末,是因為可以做一些我自己喜歡的事。
比如我插上耳機,寫點東西就能坐上一天,這也許算是屬于我自己的一份靜谧吧。
想系統學習請參考:Playwright+Java入門
使用Playwright進行API測試
1、總體感受
和其他API的依賴比起來,感覺使用起來不是很舒服,而且感覺繁瑣呢,肯定是我研究的不夠深入,不熟引起的。
2、初始化配置
這一部分相當于httpclient的初始化用戶端操作,示例代碼如下:
@BeforeClass
public void beforeClass() {
playwright = Playwright.create();
request = playwright.request().newContext(new APIRequest.NewContextOptions()
.setBaseURL("http://localhost:8090"));
}
銷毀操作,示例代碼如下:
@AfterClass
public void afterClass() {
if (request != null) {
request.dispose();
request = null;
}
if (playwright != null) {
playwright.close();
playwright = null;
}
}
3、編寫API測試
效果如下:
image.png
image.png
4、完整代碼
這裡我僅用查詢(GET)和新增接口(POST)進行示範,完整示例代碼如下:
package com.playwight.test;
import com.microsoft.playwright.APIRequest;
import com.microsoft.playwright.APIRequestContext;
import com.microsoft.playwright.APIResponse;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.options.RequestOptions;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.Map;
import static org.testng.Assert.assertTrue;
public class TestGitHubAPI {
private Playwright playwright;
private APIRequestContext request;
@BeforeClass
public void beforeClass() {
playwright = Playwright.create();
}
/**
* get請求
*/
@Test
public void testGetAPi() {
request = playwright.request().newContext(new APIRequest.NewContextOptions()
.setBaseURL("http://localhost:8090"));
APIResponse getAPIResponse = request.get("/students");
assertTrue(getAPIResponse.ok());
System.out.println(getAPIResponse.text());
}
/**
* post請求
*/
@Test
public void testPostApi() {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
request = playwright.request().newContext(new APIRequest.NewContextOptions()
.setBaseURL("http://localhost:8090")
.setExtraHTTPHeaders(headers));
Map<String, String> data = new HashMap<>();
data.put("className", "className");
data.put("courseName", "english");
data.put("email", "[email protected]");
data.put("name", "xiaoqiang");
data.put("score", "90");
data.put("sex", "boy");
data.put("studentId", "00099");
APIResponse postAPIResponse = request.post("/studentAdd",
RequestOptions.create().setData(data));
assertTrue(postAPIResponse.ok());
System.out.println(postAPIResponse.text());
}
@AfterClass
public void afterClass() {
if (request != null) {
request.dispose();
request = null;
}
if (playwright != null) {
playwright.close();
playwright = null;
}
}
}
寫在最後
感覺還是寫API測試簡單,而且好上手,難道是我錯覺嗎?有興趣的同學可以自行嘗試!