Created
December 20, 2010 07:26
-
-
Save alaz/748122 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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