【问题标题】:How to match type of instance in ScalaTest如何匹配ScalaTest中的实例类型
【发布时间】:2017-06-04 11:43:47
【问题描述】:

我试图在使用 Matchers 的测试中断言异常类型(不要问为什么),我得到的解决方案是:

exception.getClass shouldBe classOf[FileNotFoundException]

但是看起来超级难看,有没有更好的办法?

再见

【问题讨论】:

    标签: scala scalatest matcher


    【解决方案1】:

    一种可能的解决方案是使用intercept 方法:

    val exception = intercept[NoSuchElementException] {
      List.empty[String].head // Code that throws exception
    }
    
    exception.getMessage shouldBe "head of empty list"
    

    【讨论】:

      【解决方案2】:

      你可以使用“an [] should be throwBy”匹配器:

       an [IllegalArgumentException] should be thrownBy {
          //code that should raise an exception here
       }
      

      确保您的测试类包含“匹配器”:

      class MyTestClass extends FunSuite with Matchers 
      

      【讨论】:

        猜你喜欢
        • 2020-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-25
        相关资源
        最近更新 更多