Scala XML平等问题

时间:2012-05-20 20:10:41

标签: xml scala equals

我想为case class编写一个具有toXML方法的测试用例。

import java.net.URI

case class Person(
  label: String = "author",
  name: String,
  email: Option[String] = None,
  uri: Option[URI] = None) {

  // author must be either "author" or "contributor"
  assert(label == "author" ||
    label == "contributor")

  def toXML = {
    val res =
      <author>
        <name>{ name }</name>
        {
          email match {
            case Some(email) => <email>{ email }</email>
            case None => Null
          }
        }
        {
          uri match {
            case Some(uri) => <uri>{ uri }</uri>
            case None => Null
          }
        }
      </author>

    label match {
      case "author" => res
      case _ => res.copy(label = label) // rename element
    }
  }
}

现在,我想断言,输出是正确的。因此我使用scala.xml.Utility.trim

import scala.xml.Utility.trim

val p1 = Person("author", "John Doe", Some("jd@example.com"),
  Some(new URI("http://example.com/john")))
val p2 =
  <author>
    <name>John Doe</name>
    <email>jd@example.com</name>
    <uri>http://example.com/john</uri>
  </author>

assert(trim(p1.toXML) == trim(p2))

但这会导致断言错误。如果我尝试通过比较字符串表示来断言相等性

assert(trim(p1.toXML).toString == trim(p2).toString)

没有断言错误。

我做错了什么?

1 个答案:

答案 0 :(得分:2)

首先,你的代码有问题:你有uri: Option[URI](我假设它是java.net.URI)作为构造函数参数,但是你调用了构造函数使用Option[String]

这也是问题的根源:

scala> val uri = "http://stackoverflow.com/q/10676812/334519"
uri: java.lang.String = http://stackoverflow.com/q/10676812/334519

scala> <u>{new java.net.URI(uri)}</u> == <u>{uri}</u>
res0: Boolean = false

scala> <u>{new java.net.URI(uri)}</u>.toString == <u>{uri}</u>.toString
res1: Boolean = true

发生的事情是元素的子元素是Atom,它具有其携带的data值的类型参数。在p1 URI中,这是p2(假设我们已经更正了测试以使其与构造函数匹配),并在String中{{1}} {{1}}