How to show custom error messages in ScalaTest?

Does anyone know how to display a custom error message in ScalaTest?

For example:

NumberOfElements() should equal (5) 

Shows the following message:

10 did not equal 5

But I want a more descriptive post like:

NumberOfElements must be 5.

+65
scala matcher scalatest
Jun 23 2018-11-11T00:
source share
1 answer

You are the first to ask for such a function. One way to achieve this is with the key. Something like:

 withClue("NumberOfElements: ") { NumberOfElements() should be (5) } 

This should receive an error message:

NumberOfElements: 10 not equal to 5

If you want to completely manage the message, you can write a custom layout. Or you can use a statement, for example:

 assert(NumberOfElements() == 5, "NumberOfElements should be 5") 

Can you tell us more about your use case? Why is 10, not equal to 5, not up to tobacco, and how often did you have this need?

Here is what you request:

 scala> import org.scalatest.matchers.ShouldMatchers._ import org.scalatest.matchers.ShouldMatchers._ scala> withClue ("Hi:") { 1 + 1 should equal (3) } org.scalatest.TestFailedException: Hi: 2 did not equal 3 at org.scalatest.matchers.Matchers$class.newTestFailedException(Matchers.scala:150) at org.scalatest.matchers.ShouldMatchers$.newTestFailedException(ShouldMatchers.scala:2331) scala> class AssertionHolder(f: => Any) { | def withMessage(s: String) { | withClue(s) { f } | } | } defined class AssertionHolder scala> implicit def convertAssertion(f: => Any) = new AssertionHolder(f) convertAssertion: (f: => Any)AssertionHolder scala> { 1 + 1 should equal (3) } withMessage ("Ho:") org.scalatest.TestFailedException: Ho: 2 did not equal 3 at org.scalatest.matchers.Matchers$class.newTestFailedException(Matchers.scala:150) at org.scalatest.matchers.ShouldMatchers$.newTestFailedException(ShouldMatchers.scala:2331) 

So you can write:

 { NumberOfElements() should be (5) } withMessage ("NumberOfElements:") 
+73
Jun 23 '11 at 10:01
source share



All Articles