微软自动化神器Playwright(八)如何进行API接口测
前言
我喜欢周末,是因为可以做一些我自己喜欢的事。
比如我插上耳机,写点东西就能坐上一天,这也许算是属于我自己的一份静谧吧。
想系统学习请参考:PlaywrightJava入门使用Playwright进行API测试1、总体感受
和其他API的依赖比起来,感觉使用起来不是很舒服,而且感觉繁琐呢,肯定是我研究的不够深入,不熟引起的。2、初始化配置
这一部分相当于httpclient的初始化客户端操作,示例代码如下:BeforeClasspublicvoidbeforeClass(){playwrightPlaywright。create();requestplaywright。request()。newContext(newAPIRequest。NewContextOptions()。setBaseURL(http:localhost:8090));}
销毁操作,示例代码如下:AfterClasspublicvoidafterClass(){if(request!null){request。dispose();requestnull;}if(playwright!null){playwright。close();playwrightnull;}}3、编写API测试
效果如下:
image。png
image。png4、完整代码
这里我仅用查询(GET)和新增接口(POST)进行演示,完整示例代码如下:packagecom。playwight。test;importcom。microsoft。playwright。APIRequest;importcom。microsoft。playwright。APIRequestContext;importcom。microsoft。playwright。APIResponse;importcom。microsoft。playwright。Playwright;importcom。microsoft。playwright。options。RequestOptions;importorg。testng。annotations。AfterClass;importorg。testng。annotations。BeforeClass;importorg。testng。annotations。Test;importjava。util。HashMap;importjava。util。Map;importstaticorg。testng。Assert。assertTrue;publicclassTestGitHubAPI{privatePlaywrightplaywright;privateAPIRequestContextrequest;BeforeClasspublicvoidbeforeClass(){playwrightPlaywright。create();}get请求TestpublicvoidtestGetAPi(){requestplaywright。request()。newContext(newAPIRequest。NewContextOptions()。setBaseURL(http:localhost:8090));APIResponsegetAPIResponserequest。get(students);assertTrue(getAPIResponse。ok());System。out。println(getAPIResponse。text());}post请求TestpublicvoidtestPostApi(){MapString,StringheadersnewHashMap();headers。put(ContentType,applicationjson);requestplaywright。request()。newContext(newAPIRequest。NewContextOptions()。setBaseURL(http:localhost:8090)。setExtraHTTPHeaders(headers));MapString,StringdatanewHashMap();data。put(className,className);data。put(courseName,english);data。put(email,xiaoqiangqq。com);data。put(name,xiaoqiang);data。put(score,90);data。put(sex,boy);data。put(studentId,00099);APIResponsepostAPIResponserequest。post(studentAdd,RequestOptions。create()。setData(data));assertTrue(postAPIResponse。ok());System。out。println(postAPIResponse。text());}AfterClasspublicvoidafterClass(){if(request!null){request。dispose();requestnull;}if(playwright!null){playwright。close();playwrightnull;}}}写在最后
感觉还是写API测试简单,而且好上手,难道是我错觉吗?有兴趣的同学可以自行尝试!