在构建有效负载时动态设置XML标记值

问题描述 投票:1回答:2

我正在尝试使用空手道进行自动测试。

我有一个XML有效负载。

我有一个静态XML有效负载,我正在从一个文件中读取,我想在循环中调用我的服务。

对于每个调用,我想动态替换标记名称的值。

我怎么做到这一点?

EG

下面是我的主要功能,它在循环中调用我的常用功能

Feature: Loop Call
Background:
* def common = call read('classpath:CommonFeatures.feature')

Scenario:
* table table
    | payload_file    | field_tag  | field_value |
    | 'HappyPath.xml' | 'car_fuel' | 'Gas'     |
    | 'HappyPath.xml' | 'car_color'| 'Red'     |

* def response = call read('classpath:Car.feature')  table

Car.feature

Feature: Common
Scenario:
    * print payload_file
    * print field_tag
    * print field_value
    * xml payload = read('classpath:/payload/'+payload_file)
    * print payload
    * set payload/$field_tag = field_value

这是我在设置field_tag值时遇到问题的地方。

我有其他选择这样做,比如编写一个小的java脚本方法来替换标记值或使用DOMParser或SAXParser来执行相同操作的小型java类。

但是我想知道是否有任何空手道的构建方式来执行相同的操作。

如果我使用var parser = new DOMParser(),还使用java脚本方法替换标记值;似乎DOMParser无法使用。有没有办法让它可用?

testing automation karate
2个回答
2
投票

我想如果你仔细阅读这个样本,它会回答你所有的问题:

https://github.com/intuit/karate/blob/master/karate-junit4/src/test/java/com/intuit/karate/junit4/xml/xml.feature

例如,您可以使用set关键字替换值,以及替换整个XML块(可以包含标记):

Scenario: set xml chunks using xpath
    * def req = read('envelope1.xml')
    * def phone = '123456'
    * def search = 
    """
    <acc:getAccountByPhoneNumber>
        <acc:phoneNumber>#(phone)</acc:phoneNumber>
    </acc:getAccountByPhoneNumber>
    """
    * set req /Envelope/Body = search
    * match req ==
    """
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:acc="http://foo/bar">
        <soapenv:Header />
        <soapenv:Body>
            <acc:getAccountByPhoneNumber>
                <acc:phoneNumber>123456</acc:phoneNumber>
            </acc:getAccountByPhoneNumber>
        </soapenv:Body>
    </soapenv:Envelope>
    """

请不要考虑使用DOMParser等,您可以通过Karate语法执行任何操作。


1
投票

感谢Peter的所有帮助和示例。

我觉得这是实现这一目标的最佳方式。

写了一个小的javascript函数

   """
    * def replaceTag =
      """
      function(x){
        karate.setXml('temp', x.payload);
        karate.pretty(karate.get('temp'));
        if (x.field_tag) karate.set('temp', x.field_tag, x.field_value);
        return karate.get('temp');
      }
    """

并从下面的Car.feature中调用它,我得到动态替换的有效负载。

Feature: Common
Scenario:
    * print payload_file
    * print field_tag
    * print field_value
    * xml payload = read('classpath:/payload/'+payload_file)
    * print payload
    * def args = { payload: #(payload), field_tag: #(field_tag), field_value: #
          (field_value)}
    * print args
    * xml payload = call common.replaceTag args

注意:我必须升级Karate 0.7.0版本才能使用karate.setXml方法。

© www.soinside.com 2019 - 2024. All rights reserved.