【问题标题】:Using karate built-in functions and api使用空手道内置函数和api
【发布时间】:2019-06-17 17:12:54
【问题描述】:

好的,所以我将解释我的场景是什么以及我如何使用空手道来实现它。但我正在寻找一种更好的方法来使我的测试更具可读性,并且还想使用空手道的 api 而不是过多的 javascript。

场景:我有一个用于我正在测试的 api 端点的过滤器参数,这个过滤器参数采用键值对的 json 对象。所以我做了以下

  1. 已经创建了一个 filter-template.js 如下:
function() {
    var filter_params = {
        jobId:null,
        customerIds:[],
        filterValues1:[],
        filterValues2:[], 
    };
    return filter_params;
}
  1. 我在空手道场景中阅读了这个模板,因为这是一个模板,所以在运行时我设置了这个模板中的值并运行测试。我将为键值对设置不同的值,因此每个测试都会设置自己的过滤条件。 这是通过编写自定义 js 函数来完成的,该函数将模板作为参数以及过滤条件值(参考下面的 arg 函数参数),将传递的条件设置为特定键,然后返回 json 对象。代码如下:
Scenario: Set filter scenario
    * def filter_template = call read('filter-template.js')
    * def filter_vals_list = [1001,1002]
    * def filter_condition = { cnd1: 'foo', cnd2: '#(filter_vals_list)' }
    * def setFilter =
    """
      function(arg) {
        var i;
        var filter = arg.template;
        filter.jobId = arg.condition.cnd1;
        for(i=0;i<arg.condition.cnd2.length;i++)
        {
          filter.filterValues1.add(arg.condition.cnd2.get(i));
        }
        return filter;
      }
    """
    * def getFilter = call setFilter { template: '#(filter_template)', 
      condition: '#(filter_condition)' }

然后我将 getFilter 作为参数传递给我的 api 请求。

我希望了解的是:

  1. 在设置过滤器时如何避免使用上面的 JS 循环?
  2. 使用 karate 的内置函数(如 karate.map()karate.forEach())来简化测试。
  3. 如果可能的话,任何更好的方法来解决这种情况。

非常感谢您的帮助和指导。

【问题讨论】:

    标签: karate


    【解决方案1】:

    据我了解,我在下面简化了您的场景:

    * def filter_vals_list = [ 1001, 1002 ]
    * def job_id = 'foo'
    * def filter_template =
    """
    {
      jobId: '#(job_id)',
      customerIds: [],
      filterValues1: '#(filter_vals_list)',
      filterValues2: [], 
    }
    """
    

    如果我错过了什么,请告诉我。内嵌表达式请参考:https://github.com/intuit/karate#embedded-expressions

    现在,您可以轻松地为模板使用可重复使用的 JSON,只需将最后一步更改为以下,是的 - 嵌入式表达式即使在可重复使用的 JSON 文件中也有效!

    * def filter_template = read('filter-template.json')
    

    尝试data-driven Scenario Outline 后,您可能会得到更好的想法。所以希望这能说明你是如何不必要地用 JS 使事情复杂化的!你甚至不需要karate.map() 等。

    【讨论】:

    • 感谢您的简化。就像使用嵌入式表达式一样。
    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多