使用 groovy 脚本断言比较 SoapUI 中的两个字符串的正确方法是什么?

What is the right way to compare two strings in SoapUI with groovy script assertion?

我需要在 SoapUI 中比较两个字符串。第一个来自存储在我本地目录中的文本文件,第二个来自我从 REST API 操作获得的 XML 响应。在比较这两个字符串之前,我对它们使用了一些方法来删除 header,因为它们包含诸如日期和处理时间之类的信息,每次肯定都不同。

下面是我试过的。

def xml = messageExchange.responseContentAsXml
String fileData = new File("C://Users/362784/project/outputPGB123.txt").text

String responseContent = new XmlSlurper().parseText(xml)

String fileDataFiltered = fileData.substring(fileData.indexOf("PASSED :"))
String responseContentFiltered = responseContent.substring(responseContent.indexOf("PASSED :"))

log.info(fileDataFiltered)
log.info(responseContentFiltered)

assert fileDataFiltered == responseContentFiltered

这是我收到的错误

SoapUI error message

和我两个一模一样的log.info

log.info

Here's what the XML response looks like

我是 SoapUI 的新手,我不确定这两者实际上在比较什么,但我已经在 https://www.diffchecker.com/diff 上检查了它们的 log.info 并且内容是相同的。但是,这个断言returns出错了。

任何人都可以指出我做错了什么以及如何获得通过的结果吗?

在 Java/Groovy 中,您可以像这样比较字符串值是否相等:

assert fileDataFiltered.equals(responseContentFiltered)

看看是否能解决您的问题。

例如,== 比较器可以比较即使文本值相同也可能失败的对象实例。有关更深入的解释,请参阅 here

编辑:

看过你的样本后,你比较的值似乎在 XML 字符数据 (CDATA) 中。

考虑以下来自 here 的示例:

一些XML:

def response = '''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
   xmlns:sam="http://www.example.org/sample/">
   <soapenv:Header/>
   <soapenv:Body>
      <sam:searchResponse>
         <sam:searchResponse>
            <item><id>1234</id><description><![CDATA[<item><width>123</width><height>345</height><length>098</length><isle>A34</isle></item>]]></description><price>123</price>
            </item>
         </sam:searchResponse>
      </sam:searchResponse>
   </soapenv:Body>
</soapenv:Envelope>
'''

然后使用 XmlSlurper 访问 CDATA 节点:

def Envelope = new XmlSlurper().parseText(response)
def cdata = Envelope.Body.searchResponse.searchResponse.item.description
log.info cdata
log.info cdata.getClass()
assert cdata instanceof groovy.util.slurpersupport.NodeChildren

如您所见,返回的值是对象NodeChildren。您可以将其转换为字符串:

log.info cdata.toString()
log.info cdata.toString().getClass()

所以让我们做一个比较(根据 cfrick 的评论,您可以使用 == 或 .equals())

def expectedCdata = '<item><width>123</width><height>345</height>length>098</length><isle>A34</isle></item>'

if (cdata.toString().equals(expectedCdata)) { log.info 'Equal' }
else {log.info 'Different'}

还是失败了???

嗯,这是因为使用 log.info 打印时残留的换行符并不明显,如果您删除空格,它在这种情况下有效:

if (cdata.toString().replaceAll("\s","").equals(expectedCdata)) { log.info 'Equal' }
else {log.info 'Different'}

如您所见,可能的失败有很多级别。你必须克服它。