如何在抛出异常后在Try构造中测试正确的返回String?

时间:2017-11-26 18:29:46

标签: scala tdd scalatest

我想测试是否有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],但是他们只让我检查常见的异常内容,但是如果抛出这种异常则不会检查返回值。我忽略了什么吗?

最简单的方法是什么?

1 个答案:

答案 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")
  }