scala - 如何通过检查不正确的字符串模式来编写测试以进行解析
问题描述
我想编写测试代码来检查带有逗号分隔符的数字字符串的解析。代码是:
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"
}
解决方案
查看 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
推荐阅读
- python - 并排差异不再适用于 VS Code 中的 python 文件
- python - VSCode:如何删除“测试框架......未安装。安装?” 从多文件夹工作区
- excel - filename.xls 的文件格式和扩展名不匹配。文件可能已损坏或不安全
- reactjs - 捆绑连接到应用商店的 NPM 包
- node.js - 基本网络理解
- vb.net - 每次启动应用程序时随机程序集/应用程序名称 VB.NET 代码
- vue.js - Vuejs 不能在模板中使用 lodash 但它适用于代码
- java - 如何将 javafx 场景设置为没有图标?
- react-native - react-native android studio 留下空模块
- c# - 使用 DbCommand.ExecuteNonQueryAsync() > 0 时未在数据库上执行查询;