ScalaTest - how to check that all items of sequence match the predicate?

Viewed 141

Is there a way to show better error message? For example, below code

it should "check that items satisfy predicate" in {
  List(1,2,3,4,5,6).forall(x => x < 5) should equal (true)
}

only gives me following error without any description:

"false did not equal true"

Predicate can not only be least expression, but any other function. For least I found https://www.scalatest.org/user_guide/using_matchers#inspectorShorthands.

3 Answers

can not only be least expression, but any other function

Using inspector try

forAll (xs) { x => assert(pred(x)) }

where pred: T => Boolean, which output informative error message with failing index and predicate, something like

- should check that items satisfy predicate *** FAILED ***
  forAll failed, because: 
    at index 4, pred(x) was false (HelloSpec.scala:41) 
  in List(1, 2, 3, 4, 5, 6) (HelloSpec.scala:41)

  List(1,2,3,4,5,6).foreach { _ should be < 5 }

You can change the question from

"check that items satisfy predicate"

to

"check that all the items in the list are smaller than 5"

and then the answer is more meaningful.

If you want a more meaningful answer, you can call fail, like

fail("I've got a bad feeling about this.")

You can also use assertions in many ways, read this for more information. Example:

assume(database.isAvailable, "The database was down again")
Related