我想测试是否有IOException
抛出,以及" []"的正确String
值退回。我只能检查异常消息和其他内容,但我无法断言" []"
def readJsonFile(myJson: String): String =
Try {
FileSystems.getDefault().getPath(myJson)
} match {
case Success(path) => new String(Files.readAllBytes(path))
case Failure(ioe: IOException) => "[]"
case Failure(e) => sys.error(s"There was a problem with: $e")
}
我检查了assertThrows[IOException]
和intercept[IOException]
,但是他们只让我检查常见的异常内容,但是如果抛出这种异常则不会检查返回值。我忽略了什么吗?
最简单的方法是什么?
答案 0 :(得分:4)
这里的问题是IOException
被抛出Try
之外。如果您阅读Try
内的文件,它可能会满足您的期望:
def readJsonFile(myJson: String): String =
Try {
Files.readAllBytes(FileSystems.getDefault().getPath(myJson))
} match {
case Success(bytes) => new String(bytes)
case Failure(ioe: IOException) => "[]"
case Failure(e) => sys.error(s"There was a problem with: $e")
}