首页 > 解决方案 > 如何通过检查不正确的字符串模式来编写测试以进行解析

问题描述

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

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"
  }

标签: scalascalatestscopt

解决方案


查看 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

推荐阅读