Skip to content

Instantly share code, notes, and snippets.

@alaz
Created December 20, 2010 07:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alaz/748122 to your computer and use it in GitHub Desktop.
Save alaz/748122 to your computer and use it in GitHub Desktop.
import reflect.{Manifest, ClassManifest}
import org.scalatest.matchers.{Matcher,MatchResult}
trait CustomMatchers {
/**
* Based on http://daily-scala.blogspot.com/2010/01/overcoming-type-erasure-in-matching-1.html
*/
class ConformMatcher[A](implicit m: Manifest[A]) extends Matcher[AnyRef] {
override def apply(obj: AnyRef) = {
def deepConformance[B,C](desired: Manifest[B], actual: Manifest[C]): Boolean = {
def args = desired.typeArguments.zip(actual.typeArguments) forall {
case (d, a) =>
deepConformance(d, a)
}
desired >:> actual && args
}
/* FIXME: this does not work because of "singleType". We need the actual
result's Manifest here. Original "apply" in Matcher trait does not
take possible Manifest into account unfortunately. */
MatchResult(deepConformance(m, ClassManifest.singleType(obj)),
obj+" is not subtype of "+m.erasure,
obj+" is a subtype of "+m.erasure)
}
}
def conformTo[A](implicit m: Manifest[A]) = new ConformMatcher[A]()
}
import org.scalatest.Spec
import org.scalatest.matchers.MustMatchers
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class matcherSpec extends Spec with MustMatchers with CustomMatchers {
describe("be subtypeOf matcher") {
it("must conform List[Int] to Seq[Int]") {
List(1) must conformTo[Seq[Int]]
}
it("must not conform List[String] to Seq[Int]") {
List(1) must not (conformTo[Seq[String]])
}
it("must conform List[List[String]] to List[Seq[String]]") {
List(List("a")) must conformTo[List[Seq[String]]]
}
it("must not conform List[Seq[String]] to List[List[String]]") {
List(List("a").toSeq) must not (conformTo[List[List[String]]])
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment