I want to write a test case for a case class, that has a toXML method.
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 output is correct. Therefor I use 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))
But this will cause an assertion error. If I try to assert equality by comparing the String representations
assert(trim(p1.toXML).toString == trim(p2).toString)
there’s no assertion error.
What am I doing wrong?
First of all there’s something wrong with your code: you have
uri: Option[URI](which I’m assuming isjava.net.URI) as a constructor argument, but then you call the constructor with anOption[String].This is also the source of your problem:
What’s happening is that the element’s child is an
Atom, which has a type parameter for thedatavalue it carries. In yourp1this is aURI(assuming we’ve corrected the test so that it matches the constructor), and inp2it’s aString.