微软出品自动化神器【Playwright+Java】系列(八) 之 使用 Playwright进行API接口测试

前言

我喜欢周末是因为,可以做一些我自己喜欢的事。

比如我插上耳机,写点东西就能坐上一天,这也许算是属于我自己的一份静谧吧。

想系统学习请参考: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", "xiaoqiang@qq.com");
        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测试简单,而且好上手,难道是我错觉吗?有兴趣的同学可以自行尝试!

使用 Playwright 和 Python 可以方便地进行自动化测试。以下是一个简单示例,演示如何使用 Playwright 进行浏览器自动化测试: 1. 安装 Playwright 和 Python: 在命令行中运行以下命令来安装 Playwright 和 Python: ``` pip install playwright ``` 2. 初始化 Playwright: 在命令行中运行以下命令来初始化 Playwright: ``` playwright install ``` 3. 编写测试脚本: 创建一个 Python 脚本,并导入所需的模块和类: ```python from playwright.sync_api import sync_playwright def test_example(): with sync_playwright() as playwright: browser = playwright.chromium.launch() context = browser.new_context() page = context.new_page() # 打开网页 page.goto('https://www.example.com') # 在文本框中输入内容 page.fill('input[name="q"]', 'Playwright') # 点击搜索按钮 page.click('button[type="submit"]') # 等待搜索结果加载完毕 page.wait_for_load_state() # 断言页面标题是否包含关键字 assert 'Playwright' in page.title() # 关闭浏览器 context.close() browser.close() if __name__ == '__main__': test_example() ``` 在上述代码中,我们使用 Playwright 启动 Chromium 浏览器,创建一个新的页面,并在页面上执行一系列操作,包括打开网页、填充文本框、点击按钮、等待加载和断言页面标题。最后关闭浏览器。 4. 运行测试脚本: 在命令行中运行以下命令来执行测试脚本: ``` python test_script.py ``` 这将启动浏览器并执行测试脚本中的操作。如果一切正常,你将看到测试结果输出。 这只是一个简单的示例,Playwright 还提供了更多功能和 API,例如处理表单、截图、模拟用户行为等。你可以查阅 Playwright 的官方文档以了解更多详细信息和示例代码。希望这个示例能帮助你入门 Playwright 和 Python 自动化测试!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值