Wil*_*ill 7 java xml groovy compare
我正在编写单元测试来检查一些XML构建器.
现在我遇到了预期结果和实际结果之间的语法差异问题,尽管它们的语义相同.
例:
预期结果:
<parent><child attr="test attribute">text here</child></parent>
Run Code Online (Sandbox Code Playgroud)
实际结果:
<parent>
<child attr="test attribute">
text here
</child>
</parent>
Run Code Online (Sandbox Code Playgroud)
我尝试使用XmlUtil.serialize()来规范化xml,但这似乎保留了空白,留下了语法上的差异.
我怎样才能获得xml字符串的规范化/规范形式,以使我的测试更加健壮?
我正在编写一个Grails应用程序,所以我对Groovy或Java中的任何解决方案都很好.
Ben*_*chi 17
您可以像这样使用Groovy XMLUnit实用程序:
XMLUnit.setIgnoreWhitespace(true)
XMLUnit.setIgnoreComments(true)
XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true)
XMLUnit.setNormalizeWhitespace(true)
XMLUnit.compareXML(expectedXml, actualXml)
Run Code Online (Sandbox Code Playgroud)
比较XML文件而忽略语法差异.
该问题和接受的答案(截至今天)对应于XMLUnit的旧版本。
对于那些有兴趣了解如何在 Groovy 上使用XMLUnit v2 执行此操作的人:
def "XMLs must be identical"() {
setup:
def control = '<foo><bar></bar></foo>'
def test = '''
<foo>
<bar></bar>
</foo>
'''
when:
Diff d = DiffBuilder.compare(Input.fromString(control))
.withTest(Input.fromString(test))
.ignoreWhitespace()
.ignoreComments()
.normalizeWhitespace()
.build()
then:
!d.hasDifferences()
}
Run Code Online (Sandbox Code Playgroud)
也许有一种“更绝妙”的方式来做到这一点,但我认为用于说明目的是可以的:)