Skip to content

Instantly share code, notes, and snippets.

@muuki88
Created January 28, 2012 12:54
Show Gist options
  • Save muuki88/1694204 to your computer and use it in GitHub Desktop.
Save muuki88/1694204 to your computer and use it in GitHub Desktop.
Custom Scalatest Matchers
//Copied from ShouldMatchers and Matchers
private object ShouldMethodHelper {
def shouldMatcher[T](left: T, rightMatcher: Matcher[T]) {
rightMatcher(left) match {
case MatchResult(false, failureMessage, _, _, _) => throw newOverridenTestFailedException(failureMessage)
case _ => ()
}
}
}
private def newOverridenTestFailedException(message: String): Throwable = {
val fileNames = List("Matchers.scala", "ShouldMatchers.scala", "MustMatchers.scala")
val temp = new RuntimeException
val stackDepth = temp.getStackTrace.takeWhile(stackTraceElement => fileNames.exists(_ == stackTraceElement.getFileName) || stackTraceElement.getMethodName == "newTestFailedException").length
// if (stackDepth != 4) throw new OutOfMemoryError("stackDepth in Matchers.scala is: " + stackDepth)
new TestFailedException(message, stackDepth)
}
final class ResultsShouldWrapper(left: Results) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* javaList should equal (someOtherResults)
* ^
* </pre>
*/
def should(rightMatcher: Matcher[Results]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcher)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* results should have length (3)
* ^
* </pre>
*/
def should(haveWord: HaveWord): ResultOfHaveWordForResults = {
new ResultOfHaveWordForResults(left, true)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* results should not have length (3)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForResults = {
new ResultOfNotWordForResults(left, false)
}
//Implicit conversion
implicit def convertToResultsShouldWrapper[T](o: Results): ResultsShouldWrapper = new ResultsShouldWrapper(o)
}
//This does the actual matching
final class ResultOfHaveWordForResults(left: Results, shouldBeTrue: Boolean) {
def contain(content: List[Any]) = {
println("It works")
/* throw newOverridenTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
left,
expectedLength))*/
}
}
final class ResultOfNotWordForResults(left: Results, shouldBeTrue: Boolean) extends ResultOfNotWordForAnyRef(left, shouldBeTrue)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment