Scala 断言抛出了正确的异常
我有一个方法Scala 断言抛出了正确的异常,scala,Scala,我有一个方法ESV.allocate(BLOCK_NUMBER+1),它只返回一个异常包装在故障中: Failure(new Exception("Tried to allocate more than available memory")) 然而,我不知道如何测试它 我尝试使用FunSuite,并将其放在单元测试中: assert(ESV.allocate(BLOCK_NUMBER + 1) == Failure(new Exception("Tried to allocate more t
ESV.allocate(BLOCK_NUMBER+1)
,它只返回一个异常
包装在故障中
:
Failure(new Exception("Tried to allocate more than available memory"))
然而,我不知道如何测试它
我尝试使用FunSuite,并将其放在单元测试中:
assert(ESV.allocate(BLOCK_NUMBER + 1) == Failure(new Exception("Tried to allocate more than available memory")))
但是,测试失败,并显示以下消息:
Failure(java.lang.Exception: Tried to allocate more than available memory) did not equal Failure(java.lang.Exception: Tried to allocate more than available memory)
这可能是因为我在断言中实例化了一个不同的异常
对象,它与我正在测试的方法返回的对象相比并不相等
那么如何检查方法返回的结果呢?比较类,而不是比较绝对值
assert(ESV.allocate(BLOCK_NUMBER + 1).getClass == classOf[Failure[_]])
如果您还想检查异常消息,则
assert((ESV.allocate(BLOCK_NUMBER + 1).getClass == classOf[Failure[_]]) && (ESV.allocate(BLOCK_NUMBER + 1).failed.get.getMessage == Failure(new Exception("Tried to allocate more than available memory")).failed.get.getMessage))
或
更好的解决方案
implicit class TryUtils[A](something: Try[A]) {
def compare[B](other: Try[B]): Boolean = {
(something, other) match {
case (Success(a), Success(b)) => a == b
case (Failure(a), Failure(b)) => a.getClass == b.getClass && (a.getMessage == b.getMessage)
case (_, _) => false
}
}
}
用法:
assert(ESV.allocate(BLOCK_NUMBER + 1) compare Failure(new Exception("Tried to allocate more than available memory")))
比较类而不是比较绝对值
assert(ESV.allocate(BLOCK_NUMBER + 1).getClass == classOf[Failure[_]])
如果您还想检查异常消息,则
assert((ESV.allocate(BLOCK_NUMBER + 1).getClass == classOf[Failure[_]]) && (ESV.allocate(BLOCK_NUMBER + 1).failed.get.getMessage == Failure(new Exception("Tried to allocate more than available memory")).failed.get.getMessage))
或
更好的解决方案
implicit class TryUtils[A](something: Try[A]) {
def compare[B](other: Try[B]): Boolean = {
(something, other) match {
case (Success(a), Success(b)) => a == b
case (Failure(a), Failure(b)) => a.getClass == b.getClass && (a.getMessage == b.getMessage)
case (_, _) => false
}
}
}
用法:
assert(ESV.allocate(BLOCK_NUMBER + 1) compare Failure(new Exception("Tried to allocate more than available memory")))
对于
成功
,是否有一种相当于失败
的方法?@octavian您可以像这样在成功时直接执行获取
.get@octavian用更好的解决方案编辑答案使用比较
是否有一种方法相当于失败
获得成功
?@octavian您可以这样做直接获得成功(“a”)。get
@octavian用更好的解决方案编辑答案使用比较