在单元测试中比较 scala.xml.Elem 对象
我有两个 scala.xml.Elem 对象(实际的、预期的)。我使用的是 JUnit 4,但也包含了 XMLUnit 1.3。
有没有简单的方法可以比较两个对象的相等性,忽略 XML 中的属性顺序和无关紧要的空格?
我尝试了 XMLUnit.assertXMLEqual(),但它抱怨类型是 scala.xml.Elem。
我知道我可以使用 equals
或 ==
,但我希望让断言在两个值不相等时打印它们的好处。如果我使用assertTrue(actual.equals(expected)),并且它们不相等,则唯一的输出将是“断言失败”。
I have two scala.xml.Elem
objects (actual, expected). I am using JUnit 4, but have also included XMLUnit 1.3.
Is there any easy way to compare the two objects for equality, ignoring attribute order and insignificant whitespace in the XML?
I tried XMLUnit.assertXMLEqual()
, but it complains that the types are scala.xml.Elem
.
I know that I can use equals
or ==
, but I would like the benefit of having the assertion print the two values when they are not equal. If I use assertTrue(actual.equals(expected))
, and they are not equal, the only output will be "assertion failed".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您想与忽略空格的 XML
Elem
对象进行比较,您可以使用scala.xml.Utility.trim
方法从它们中删除空格。如果您使用 XML 文字,Scala 并不关心属性的顺序:
我建议使用 ScalaTest 进行单元测试你有
ShouldMatchers
:If you want to compare to XML
Elem
objects ignoring whitespaces you can remove the whitespaces from them withscala.xml.Utility.trim
method.Scala does not care about the order of the attributes if you use XML literals:
I would recommend ScalaTest for unit testing there you have the
ShouldMatchers
:使用允许传递自定义消息的
assertTrue
版本和(例如)
diff
来生成后代节点不相等的字符串Use the version of
assertTrue
that allows passing custom messagesand (for example)
diff
to produce the string with the descendand nodes that aren't equal早期的答案对我很有帮助,尽管我发现有时我想检查较大的 XML 块,并且显示两个 XML 块的失败比较有点难以阅读。此方法将尝试首先递归到子元素来比较它们,因此如果深度嵌套的元素不正确,它将显示更简洁的错误。根据您的 XML,这可能无法为您提供足够的上下文来找出实际失败的位置,但我发现它很有用。
The earlier answers were helpful to me, though I found that sometimes I wanted to check a larger chunk of XML and the failure comparison showing both chunks of XML was a bit hard to read. This method will try to recurse down into child elements first to compare those, so if a deeply nested element is incorrect it will show a much more concise error. Depending on your XML this might not give you enough context to work out where it's actually failing, but I find it useful.
我修改了 @Nick 的代码以与 JDom2 一起使用。在他的代码中,由于
zip
的工作原理,如果expectedXML
具有actualXML
中不存在的尾随元素,则测试会通过。我修复了该错误,并将尾随元素的比较设为可选:我编写了此特征以混合到测试代码中:
我以这种方式调用测试:
I modified @Nick's code to work with JDom2. In his code, because of how
zip
works, ifexpectedXML
has trailing elements that are not inactualXML
, the test passes. I fixed that bug, and made the comparison of trailing elements optional:I wrote this trait to mix into the test code:
I invoked the test this way: