Last active
July 28, 2016 12:56
-
-
Save ittaiz/c775c382d6b53f74b6e3cd53d9169127 to your computer and use it in GitHub Desktop.
Polymorphic matching
This file contains 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
class FruitTest extends SpecificationWithJUnit { | |
trait Fruit | |
case class Apple(color: String) extends Fruit | |
case class Peach(ripeness: Double) extends Fruit | |
def aColorfulApple(color: String): Matcher[Fruit] = { | |
val appleMatcher: Matcher[Apple] = be_===(color) ^^ { a: Apple => | |
a.color aka "apple color" | |
} | |
val fruitMatcher: Matcher[Fruit] = (_: Fruit) match { | |
case apple: Apple => appleMatcher.apply(MustExpectable[Apple](apple)) | |
case _ => ko("something which is not an apple") | |
} | |
fruitMatcher | |
} | |
"match an apple from a set of fruits" in { | |
Set(Apple("red"), Apple("green"), Peach(0.3)) must contain(aColorfulApple("green")) | |
} | |
} |
yup, this really looks nice in tests
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I actually have a very different way of implementing this:
While this is a bit annoying to write (although you can copy-paste or even template most of this), it allows very flexible syntax on the usage site:
The same principal applies to all of the other subtypes, and you can mix-and-match them safely.