Compare scala.xml.Elem object in unit test

前端 未结 4 1902
执笔经年
执笔经年 2021-02-19 06:21

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 objec

4条回答
  •  深忆病人
    2021-02-19 06:53

    If you want to compare to XML Elem objects ignoring whitespaces you can remove the whitespaces from them with scala.xml.Utility.trim method.

    scala> val a = bar
    a: scala.xml.Elem = bar
    
    scala> val b =    bar   
    b: scala.xml.Elem =    bar   
    
    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
    

    Scala does not care about the order of the attributes if you use XML literals:

    scala> val a = 
    a: scala.xml.Elem = 
    
    scala> val b = 
    b: scala.xml.Elem = 
    
    scala> a == b
    res22: Boolean = true
    

    I would recommend ScalaTest for unit testing there you have the ShouldMatchers:

    // Scala repl started with scalatest-1.2.jar in the classpath
    
    scala> val a = bar
    a: scala.xml.Elem = bar
    
    scala> val b = bar
    b: scala.xml.Elem = bar
    
    scala> a should equal(b)
    
    scala> val b = bar2
    b: scala.xml.Elem = bar2
    
    scala> a should equal(b)
    org.scalatest.TestFailedException: bar did not equal bar2
        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 .(:15)
        at .()
        at RequestResult$.(:9)
        at RequestResult$.()
        at RequestResult$scala_repl_result()
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.Delega...
    

提交回复
热议问题