Leif Ericson Leif Ericson - 1 month ago 4x
Scala Question

Distinguishing between expected and actual values in ScalaTest using matchers

In ScalaTest you can distinguish between expected and actual values in assertions using the

macro like this:

assertResult(expected) { actual }

This will print a "
Expected X, but got Y
" message when the test fails, instead of the usual "
X did not equal Y

How would you achieve a similar thing using (
, etc.) Matchers?


The matchers build their own error messages, so for the standard matchers you simply need to know that the actual value is the one on the left. If you want to change the message, I believe you'll have to write a custom matcher like in http://www.scalatest.org/user_guide/using_matchers#usingCustomMatchers (the example below neglects TripleEquals, etc.):

trait MyMatchers {
  class MyEqualMatcher[A](expectedValue: A) extends Matcher[A] {
    def apply(left: A) = {
        left == expectedValue,
        s"""Expected $expectedValue, but got $left""",
        s"""Got the expected value $expectedValue"""

  def equalWithMyMessage[A](expectedValue: A) = new MyEqualMatcher(expectedValue) // or extend Matchers and override def equal

// in test code extending the trait above
x should equalWithMyMessage(y)