gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:17:38 26 4
gpt4 key购买 nike

这是一个玩具示例:

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

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

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

"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]

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

关于scala - 使用 scalatest 测试封装在 Failure() 中的异常类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43489800/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com