抛出异常后,如何在 Try 构造中测试正确的 return 字符串?

How to test correct return String in Try construct after exception was thrown?

我想测试是否抛出 IOException 以及是否 return 编辑了“[ ]”的正确 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],但它们只让我检查常见的异常内容,但不检查 return 值,以防抛出此类异常。我是不是忽略了什么?

完成它的最简单方法是什么?

这里的问题是 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")
  }