Scala XML Equality Issues

I want to write a test case for case classwhich has a method 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
    }
  }
}

Now I want to assert that the result is correct. Therefore i usescala.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))

But this will lead to an assertion error. If I try to claim equality by comparing String representations

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

no approval error.

What am I doing wrong?

+3
source share
1 answer

First of all, something is wrong with your code: you have uri: Option[URI](which I assume is java.net.URI) as an argument to the constructor, but then you call the constructor with Option[String].

This is also the source of your problem:

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 - a String.

+2

All Articles