How to show custom failure messages in ScalaTest?

后端 未结 3 810
無奈伤痛
無奈伤痛 2021-01-31 13:29

Does anyone know how to show a custom failure message in ScalaTest?

For example:

NumberOfElements() should equal (5)

Shows the followin

3条回答
  •  你的背包
    2021-01-31 13:32

    New way since 2011: Matchers and AppendedClue1 traits. Also, for collection sizes, there are some default messages.

    import org.scalatest.{AppendedClues, Matchers, WordSpec}
    
    class SomeTest extends WordSpec with Matchers with AppendedClues {
    
      "Clues" should {
        "not be appended" when {
          "assertions pass" in {
            "hi" should equal ("hi") withClue "Greetings scala tester!"
          }
        }
        "be appended" when {
          "assertions fail"  in {
            1 + 1 should equal (3) withClue ", not even for large values of 1!"
          }
        }
        "not be needed" when {
          "looking at collection sizes" in {
            val list = List(1, 2, 3)
            list should have size 5
          }
        }
      }
    }
    

    Output looks like this:

    SomeTest:
    Clues
      should not be appended
      - when assertions pass
      should be appended
      - when assertions fail *** FAILED ***
        2 did not equal 3, not even for large values of 1! (SomeTest.scala:15)
      should not be needed
      - when looking at collection sizes *** FAILED ***
        List(1, 2, 3) had size 3 instead of expected size 5 (SomeTest.scala:21)
    

    Note that the List size message isn't great for lists with long .toString output.

    See the scaladoc for more information.


    1 I'm guessing the AppendedClues trait was inspired by this question, Bill Venners of the accepted answer is the author of this trait.

提交回复
热议问题