Karate测试Feature文件JS函数调用无法处理字符串拼接问题
Karate Scenario Outline中字符串拼接值无法传递给JS函数
我在Karate的Scenario Outline的Examples第一列写了字符串拼接表达式,这个操作在其他Feature文件里能正常运行,但把拼接后的URL传给JS函数check_hashes.js时失败,始终传递的是字面量(比如baseUrl + 'fr' + basePort)。Page和AssetType参数能正常传入JS,只有拼接后的URL不行。我试过直接传concatUrl、显式定义拼接字符串、用karate.get('url'),都没用,好像字符串拼接在JS函数调用前没执行。请问怎么把concatUrl的实际值传给check_hashes.js?
附Feature文件代码:
Feature: Asset Hash Validation Background: * def envConfig = karate.read('classpath:envs.json')[karate.env] * def baseUrl = envConfig['base_domain'] * def basePort = envConfig['base_port'] Scenario Outline: JS and CSS assets have hashes in their URLs Given url <concatUrl> Given path <Page> * def fullUrl = karate.get('url') * def params = { url: <fullUrl>, path: <Page>, assetType: <AssetType> } * def noHashCount = call read('check_hashes.js') params When method get Then status 200 And match noHashCount == 0 Examples: | concatUrl | Page | AssetType | | baseUrl + 'fr' + basePort | '/fr/home' | 'css' | | baseUrl + 'fr' + basePort | '/fr/home' | 'js' | | baseUrl + 'com' + basePort | '/en/home' | 'all' |
注:base_domain类似"http://www.example.",base_port类似":8080",需要测试多顶级域名及不同环境端口。
解决方案
问题核心是Scenario Outline的Examples表格中的表达式不会被Karate解析执行,表格内容会被当作字面量字符串处理,所以你传入JS的是"baseUrl + 'fr' + basePort"这个文本,而非拼接后的实际URL。
推荐的调整方式是拆分可变参数,在Scenario内部完成URL拼接:
修改后的Feature文件
Feature: Asset Hash Validation Background: * def envConfig = karate.read('classpath:envs.json')[karate.env] * def baseUrl = envConfig['base_domain'] * def basePort = envConfig['base_port'] Scenario Outline: JS and CSS assets have hashes in their URLs # 在Scenario内部完成URL拼接,确保表达式被执行 * def concatUrl = baseUrl + <Tld> + basePort Given url concatUrl Given path <Page> # 直接构造完整URL,避免依赖karate.get('url')的解析时机问题 * def fullUrl = concatUrl + <Page> * def params = { url: fullUrl, path: <Page>, assetType: <AssetType> } * def noHashCount = call read('check_hashes.js') params When method get Then status 200 And match noHashCount == 0 Examples: | Tld | Page | AssetType | | 'fr' | '/fr/home' | 'css' | | 'fr' | '/fr/home' | 'js' | | 'com'| '/en/home' | 'all' |
关键说明
- 把原拼接表达式拆分为固定的
baseUrl/basePort和可变的顶级域名后缀Tld,将Tld作为Examples参数 - 在Scenario内部用
* def concatUrl = baseUrl + <Tld> + basePort完成拼接,Karate会正常执行表达式得到实际URL - 直接用拼接好的变量构造
fullUrl,避免依赖karate.get('url')的延迟解析特性导致的取值问题
如果一定要保留Examples中的表达式写法,也可以用karate.eval()强制解析,但可读性较差,不推荐:
# 在Scenario中添加这一行解析concatUrl字面量 * def actualConcatUrl = karate.eval(<concatUrl>) Given url actualConcatUrl
内容的提问来源于stack exchange,提问作者Deeepdigger
相关产品推荐
相关产品推荐

