Vadim
Vadim

Reputation: 825

How to write test with checking incorrect string pattern for parsing

I want to write test code which check parsing of the string of numbers with comma delimiter. The code is:

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

Test has to check appearing of the failure with message "String should not be in pattern number with comma." when the string pattern is incorrect. For example "1,2,3," or "ew3,56,66" . How to catch the correct message?

My version (not checking the target failure message)

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

Upvotes: 0

Views: 433

Answers (1)

y_ug
y_ug

Reputation: 1124

See advanced features of 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

Upvotes: 0

Related Questions