我有两个scala.xml.Elem对象(实际的,预期的).我使用的是JUnit 4,但也包含了XMLUnit 1.3.
有没有简单的方法来比较两个对象的相等性,忽略XML中的属性顺序和无关紧要的空格?
我试过XMLUnit.assertXMLEqual(),但它抱怨类型是scala.xml.Elem.
我知道我可以使用equals或==,但我希望断言打印两个值不相等时的好处.如果我使用assertTrue(actual.equals(expected))它们并且它们不相等,则唯一的输出将是"断言失败".
mic*_*ebe 18
如果要与Elem忽略空格的XML 对象进行比较,可以使用scala.xml.Utility.trim方法从中删除空格.
scala> val a = <foo>bar</foo>
a: scala.xml.Elem = <foo>bar</foo>
scala> val b = <foo> bar </foo>
b: scala.xml.Elem = <foo> bar </foo>
scala> a == b
res8: Boolean = false
scala> import scala.xml.Utility.trim
import scala.xml.Utility.trim
scala> trim(a) == trim(b)
res9: Boolean = true
Run Code Online (Sandbox Code Playgroud)
如果使用XML文字,Scala不关心属性的顺序:
scala> val a = <foo first="1" second="2" />
a: scala.xml.Elem = <foo first="1" second="2"></foo>
scala> val b = <foo second="1" first="1" />
b: scala.xml.Elem = <foo first="1" second="1"></foo>
scala> a == b
res22: Boolean = true
Run Code Online (Sandbox Code Playgroud)
我建议您使用ScalaTest进行单元测试ShouldMatchers:
// Scala repl started with scalatest-1.2.jar in the classpath
scala> val a = <foo>bar</foo>
a: scala.xml.Elem = <foo>bar</foo>
scala> val b = <foo>bar</foo>
b: scala.xml.Elem = <foo>bar</foo>
scala> a should equal(b)
scala> val b = <foo>bar2</foo>
b: scala.xml.Elem = <foo>bar2</foo>
scala> a should equal(b)
org.scalatest.TestFailedException: <foo>bar</foo> did not equal <foo>bar2</foo>
at org.scalatest.matchers.Matchers$class.newTestFailedException(Matchers.scala:148)
at org.scalatest.matchers.ShouldMatchers$.newTestFailedException(ShouldMatchers.scala:2329)
at org.scalatest.matchers.ShouldMatchers$ShouldMethodHelper$.shouldMatcher(ShouldMatchers.scala:871)
at org.scalatest.matchers.ShouldMatchers$SeqShouldWrapper.should(ShouldMatchers.scala:1724)
at .<init>(<console>:15)
at .<clinit>(<console>)
at RequestResult$.<init>(<console>:9)
at RequestResult$.<clinit>(<console>)
at RequestResult$scala_repl_result(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.Delega...
Run Code Online (Sandbox Code Playgroud)
Vas*_*iuk 10
使用assertTrue允许传递自定义消息的版本
public static void assertTrue(java.lang.String message,
boolean condition)
Run Code Online (Sandbox Code Playgroud)
和(例如)diff生成具有不相等的下降节点的字符串
scala> val xml1 = <person><name>john</name><lastname>smith</lastname></person>
xml1: scala.xml.Elem = <person><name>john</name><lastname>smith</lastname></person>
scala> val xml2 = <person><name>jane</name><lastname>smith</lastname></person>
xml2: scala.xml.Elem = <person><name>jane</name><lastname>smith</lastname></person>
scala> assert(xml1 == xml2, xml1.child diff xml2.child mkString(", "))
java.lang.AssertionError: assertion failed: <name>john</name>
at scala.Predef$.assert(Predef.scala:91)
at .<init>(<console>:8)
at .<clinit>(<console>)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4821 次 |
| 最近记录: |