ses
ses

Reputation: 13342

scala specs2. equal check relying on toString

This test is OK, because I use toString explicitly

"have one sentence by '...'" in {

  val text1 = Text("some text...")
  text1.sentences must have size(1)

  text1.sentences(0).toString must_== "some text"
}

If without toSting the test it fails with message like:

Expected :some text
Actual   :some text

java.lang.Exception: 'some text: dictionary.Sentence' is not equal to 'some text: java.lang.String'

I understand the sense of it (in general), but since toString is invoked anyway shouldn't it check string to string then?

What is the best way to write this test to be concise? Without using toString directly.

Upvotes: 1

Views: 715

Answers (1)

cmbaxter
cmbaxter

Reputation: 35443

I think you might be confusing toString and equals. When you say what you wanted to say:

text1.sentences(0) must_== "some text"

What you are really saying is:

text1.sentences(0).equals("some text") must beTrue

If you want this to work, then you would need there to be an equals function on the Sentence class that used the toString of the sentence to compare to the incoming object (a String in this case). A simple spec showing that could look like this:

class Sentence(text:String){
  override def equals(obj:Any) = {
    this.toString == obj.toString
  }
  override def toString = text
}

class EqualitySpec extends Specification{
  "A sentence" should{
    "be equal to plain text" in {
      val sentence = new Sentence("hello world")
      sentence must be_==("hello world")
    }
  } 
}

Now this works great if that Sentence class is your own class. If it's in a third party library and you have no control over the equals function then you might be stuck with things the way that they are.

Upvotes: 1

Related Questions