Freewind
Freewind

Reputation: 198188

Writing a custom matcher for NodeSeq

I'm trying to write a simple custom matcher for NodeSeq, with scalatest v.2.0.M5b.

package test

import org.scalatest.matchers.{MatchResult, Matcher, ShouldMatchers}

import scala.xml.NodeSeq
import org.scalatest.FunSpec

class MySpec extends FunSpec with ShouldMatchers with MyMatcher {

  describe("where is wrong?") {
    it("showOK") {
      val xml = <span>abc</span>
      xml should contn("b")
    }
  }
}

trait MyMatcher {

  class XmlMatcher(str: String) extends Matcher[NodeSeq] {
    def apply(xml: NodeSeq) = {
      val x = xml.toString.contains(str)
      MatchResult(
        x,
        "aaa",
        "bbb"
      )
    }
  }

  def contn(str: String) = new XmlMatcher(str)

}

When I compile it, it reports error:

[error] /Users/freewind/src/test/scala/test/MyMacher.scala:14: overloaded method value should with alternatives:
[error]   (beWord: MySpec.this.BeWord)MySpec.this.ResultOfBeWordForAnyRef[scala.collection.GenSeq[scala.xml.Node]] <and>
[error]   (notWord: MySpec.this.NotWord)MySpec.this.ResultOfNotWordForAnyRef[scala.collection.GenSeq[scala.xml.Node]] <and>
[error]   (haveWord: MySpec.this.HaveWord)MySpec.this.ResultOfHaveWordForSeq[scala.xml.Node] <and>
[error]   (rightMatcher: org.scalatest.matchers.Matcher[scala.collection.GenSeq[scala.xml.Node]])Unit
[error]  cannot be applied to (MySpec.this.XmlMatcher)
[error]       xml should contn("b")
[error]           ^
[error] one error found
[error] (test:compile) Compilation failed

Where is wrong?


Update:

The build.sbt file I use:

name := "scalatest-test"

scalaVersion := "2.10.1"

version := "1.0"

resolvers ++= Seq("snapshots"     at "http://oss.sonatype.org/content/repositories/snapshots",
            "releases"        at "http://oss.sonatype.org/content/repositories/releases",
            "googlecode"      at "http://sass-java.googlecode.com/svn/repo"
            )

libraryDependencies += "org.scalatest" %% "scalatest" % "2.0.M5b" % "test"

And a demo project: https://github.com/freewind/scalatest-test

Upvotes: 1

Views: 247

Answers (1)

xiefei
xiefei

Reputation: 6599

For the reason why scala compiler complains see this answer.

But it seems that ScalaTest API has changed quite a bit since then, so the two solutions proposed both need some modification (tested for ScalaTest 2.0.M5b):

  • Replace All instances of NodeSeq to GenSeq[Node] so that the type matches everywhere.

    See SeqShouldWrapper class of ScalaTest.

  • Alternatively, wrap xml explicitely with the conversion function, i.e. manually setting the required type but I don't recommend this because it makes client code ugly.

    new AnyRefShouldWrapper(xml).should(contn("b"))

BTW, it is good to have a small but complete project on github for others to tweak. It makes this question much more attractive.

Upvotes: 1

Related Questions