我的方法ESV.allocate(BLOCK_NUMBER + 1)
仅返回Exception
中包含的Failure
:
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)
这可能是因为我在断言中实例化了一个不同的Exception
对象,并且它没有与我正在测试的方法返回的对象相等。
那么如何检查方法返回的结果呢?
答案 0 :(得分:2)
比较类而不是比较绝对值。
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))
或
assert((ESV.allocate(BLOCK_NUMBER + 1).getClass == classOf[Failure[_]]) && ESV.allocate(BLOCK_NUMBER + 1).failed.get.getMessage == new Exception("Tried to allocate more than available memory").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")))