Search code examples
scalascalatest

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


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.


Solution

  • 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)