0

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

以下是我尝试过的。

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 错误消息

和我的两个相同的 log.info

日志信息

这是 XML 响应的样子

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

谁能指出我做错了什么以及如何获得通过的结果?

4

1 回答 1

1

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

assert fileDataFiltered.equals(responseContentFiltered)

看看能不能解决你的问题。

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

编辑:

看过您的示例后,您正在比较的值似乎在 XML 字符数据 (CDATA) 中。

从这里考虑以下示例:

一些 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'}

正如您所看到的,有许多级别的可能失败。你必须克服它。

于 2020-06-25T08:32:24.647 回答