【问题标题】:Test type of exception encapsulated in Failure() with scalatest用scalatest封装在Failure()中的异常测试类型
【发布时间】:2017-04-19 16:55:39
【问题描述】:

这是一个玩具示例:

我有一个方法 last[T](ts: Seq[T]): Try[T] 可以返回:

  • Success 包裹的非空列表的最后一个元素,或
  • NoSuchElementException 包裹在 Failure 中。

我一直在阅读scalatest doc pertaining to TryValues 并想出了以下scalates:

"The solution" should "Find the last element of a non-empty list" in {
      last(Seq(1, 1, 2, 3, 5, 8)).success.value should equal (8)
      // ...
    }

  it should "Fail with NoSuchElementException on an empty list" in {
    // Option 1: what I would like to do but is not working
    last(Nil).failure.exception should be a[NoSuchElementException]

    // Option 2: is working but actually throws the Exception, and does not test explicitly test if was in a Failure
    a [NoSuchElementException] should be thrownBy {last(Nil).get}
} 

有没有办法让我的选项 1 起作用?

【问题讨论】:

    标签: scala scalatest


    【解决方案1】:

    你应该使用shouldBe这个词来断言类型,比如:

    test.failure.exception shouldBe a [NoSuchElementException]
    

    对于类型不相等,如:

    test.failure.exception should not be an [NoSuchElementException]
    

    查看更多: http://www.scalatest.org/user_guide/using_matchers

    【讨论】:

    • 语法确实不一致...谢谢!
    猜你喜欢
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 2015-02-15
    • 2011-01-22
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多