简体   繁体   English

Groovy 断言:要比较的 xml 节点

[英]Groovy assert: xml nodes to compare

i have an xml:我有一个xml:

<body>
    <car>
        <color>green</color>
        <nr>88</nr>
    </car>
    <car>
        <color>yellow</color>
        <nr>54</nr>
    </car>
    <car>
        <color>blue</color>
        <nr>89</nr>
    </car>
    <car>
        <color>red</color>
        <nr>17</nr>
    </car>
    <car>
        <color>white</color>
        <nr>64</nr>
    </car>
</body>

I want to make sure that the colors are white, green, blue, yellow, red (the order doesn't matter).我想确保颜色是白色、绿色、蓝色、黄色、红色(顺序无关紧要)。 So i wrote a script:所以我写了一个脚本:

import groovy.util.XmlSlurper

def pXml = new XmlSlurper().parseText('<body><car><color>green</color><nr>88</nr></car><car><color>yellow</color><nr>54</nr></car><car><color>blue</color><nr>89</nr></car><car><color>red</color><nr>17</nr></car><car><color>white</color><nr>64</nr></car></body>')
def actual = pXml.car.color.sort(true) {it.text()}
def expected = ['blue', 'green', 'red', 'white', 'yellow'].sort()
assert expected==actual

Forgive me if it looks weird, i'm new in programming.如果它看起来很奇怪,请原谅我,我是编程新手。 I tired it in online groovy parser and in SoapUI, but i always get:我在在线 groovy 解析器和 SoapUI 中厌倦了它,但我总是得到:

Caught: Assertion failed: 

assert expected==actual
       |       | |
       |       | [blue, green, red, white, yellow]
       |       false
       [blue, green, red, white, yellow]
Assertion failed: 

assert expected==actual
       |       | |
       |       | [blue, green, red, white, yellow]
       |       false
       [blue, green, red, white, yellow]

at main.run(main.groovy:6)

Kindly advice好心劝告

You can use a Set instead of sorting您可以使用 Set 而不是排序

def actual = pXml.car.color*.text() as Set
Set expected = ['blue', 'green', 'red', 'white', 'yellow']
assert expected==actual

Your problem BTW was here:顺便说一句,您的问题在这里:

def actual = pXml.car.color.sort(true) {it.text()}

That was taking all the nodes, and sorting them by their text.那就是获取所有节点,并按它们的文本对它们进行排序。

It was not returning a list of Strings, it was returning a list of Nodes.它不是返回字符串列表,而是返回节点列表。

If you want to keep using Lists, you can change this to:如果您想继续使用列表,可以将其更改为:

def actual = pXml.car.color*.text().sort(true)

To sort the String text, instead of the Nodes对字符串文本进行排序,而不是对节点进行排序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM