Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-cloud-platform/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 如何通过检查不正确的字符串模式来编写测试以进行分析_Scala_Scalatest_Scopt - Fatal编程技术网

Scala 如何通过检查不正确的字符串模式来编写测试以进行分析

Scala 如何通过检查不正确的字符串模式来编写测试以进行分析,scala,scalatest,scopt,Scala,Scalatest,Scopt,我想编写测试代码,用逗号分隔符检查数字字符串的解析。代码是: case class TestConfig(macroregions: Option[Seq[Int]] = None) object TestConfig { private val parser = new scopt.OptionParser[TestConfig]("Test") { ... opt[String]('r', "stringArrayWithNumbers")

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

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"))
}
当字符串模式不正确时,测试必须通过消息“字符串不应位于带逗号的模式编号中”来检查故障的出现情况。。例如
“1,2,3”
“ew3,56,66”
。如何捕捉正确的信息

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


请参阅scopt的高级功能:


使用
sys.error
进行验证失败很少发生recommended@cchantep非常感谢。在scala中抛出异常的更好方法是什么?最好的方法是不抛出异常。对带有验证错误的API建模的最佳方法是返回验证(monadic)类型
  "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"
  }
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