0

我想编写测试代码来检查带有逗号分隔符的数字字符串的解析。代码是:

case class TestConfig(macroregions: Option[Seq[Int]] = None)

object TestConfig {
    private val parser = new scopt.OptionParser[TestConfig]("Test") {
        ...
        opt[String]('r', "stringArrayWithNumbers")
        .....
        .validate { mrs =>
            if (mrs.matches("""\d+(?:\s*,\s*\d+)*""")) success
            else failure("String should not be in pattern number with comma.")
        }
        ....
    }

    def parseArgs(args: Array[String]): TestConfig = parser
        .parse(args, TestConfig())
        .getOrElse(sys.error("Could not parse arguments"))
}

"String should not be in pattern number with comma."当字符串模式不正确时,测试必须检查是否出现故障并显示消息。例如"1,2,3,""ew3,56,66"。如何捕捉正确的消息?

我的版本(不检查目标失败消息)

  "TestConfig" should "return failure of incorrect String pattern" in {
    val cmdLine =
      """     | --numbers 1,2,3,4,""".stripMargin
    val args = cmdLine.replace("\r\n", "").split("\\s")

    val thrown = the[RuntimeException] thrownBy TestConfig.parseArgs(args)

    thrown.getMessage should equal "Could not parse arguments"
  }
4

1 回答 1

0

查看 scopt 的高级功能:

val outCapture = new ByteArrayOutputStream
val errCapture = new ByteArrayOutputStream

Console.withOut(outCapture) {
    Console.withErr(errCapture) {
        val result = OParser.parse(parser1, args, Config())
    }
}
// Now stderr output from this block is in errCapture.toString, and stdout in outCapture.toString
于 2020-01-21T17:03:20.297 回答