使用scalatest测试Failure()中封装的异常的类型

时间:2017-04-19 07:57:59

标签: scala scalatest

这是一个玩具示例:

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

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

我一直在阅读scalatest doc pertaining to TryValues,并想出了以下的最新版本:

"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有效?

1 个答案:

答案 0 :(得分:3)

您应该使用list1 = [] for i in range(100): list1.append(i) print (list1) #print list for python 2.7 字来断言类型,例如:

shouldBe

表示类型不相等,如:

test.failure.exception shouldBe a [NoSuchElementException]

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