如何使用Karate UI获取网络面板完整响应及响应头并实现自动化测试
实现逻辑
因为目标参数接口仅支持Chrome浏览器访问,无法通过普通接口请求工具调用,所以通过Karate UI启动Chrome实例,先通过浏览器获取接口响应参数,再拼接参数到测试Web应用的URL后进行访问。
完整代码示例
Feature: 带接口参数的Web应用自动化测试 Background: # 配置启动Chrome驱动 * configure driver = { type: 'chrome', headless: false } # 替换为实际的第三方参数接口地址 * def thirdPartyApiUrl = 'https://your-internal-api-endpoint.com/get-params' # 替换为实际的待测试Web应用基础URL * def targetBaseUrl = 'https://your-test-webapp.com/home' Scenario: 获取参数后访问测试Web应用 # 1. 通过浏览器原生fetch调用参数接口,避免页面跳转更稳定 * def apiResponse = driver.executeScript("return fetch('" + thirdPartyApiUrl + "', { credentials: 'include' }).then(res => res.json())") # 2. 提取需要的两个参数,根据实际接口返回结构调整字段名 * def param1 = apiResponse.param1 * def param2 = apiResponse.param2 # 3. 拼接参数到目标Web应用URL * def testUrl = targetBaseUrl + '?param1=' + param1 + '¶m2=' + param2 # 4. 访问拼接完成的测试地址 * driver testUrl # 此处可继续添加后续Web应用UI测试逻辑 # 示例:等待页面加载完成后验证标题 * waitFor('document.title') * match driver.title contains '预期页面标题'
注意事项
- 如果参数接口需要登录态,可在调用接口前先通过Karate UI完成Chrome内的身份登录操作,
credentials: 'include'配置会自动带上当前浏览器的Cookie,保证接口请求有权限返回数据 - 不需要可视化执行时可将chrome配置的
headless改为true实现静默运行 - 参数拼接逻辑可根据实际URL规则调整,支持路径参数、哈希参数等不同传参形式
内容的提问来源于stack exchange,提问作者PARTHA DEV
相关产品推荐
相关产品推荐

