使用 scalatest 测试封装在 Failure() 中的异常类型
Test type of exception encapsulated in Failure() with scalatest
这是一个玩具示例:
我有一个方法 last[T](ts: Seq[T]): Try[T]
returns 要么:
- 包裹在
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 起作用?
您应该使用 shouldBe
词来断言类型,例如:
test.failure.exception shouldBe a [NoSuchElementException]
类型不相等,如:
test.failure.exception should not be an [NoSuchElementException]
这是一个玩具示例:
我有一个方法 last[T](ts: Seq[T]): Try[T]
returns 要么:
- 包裹在
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 起作用?
您应该使用 shouldBe
词来断言类型,例如:
test.failure.exception shouldBe a [NoSuchElementException]
类型不相等,如:
test.failure.exception should not be an [NoSuchElementException]