json - 用于匹配 json 的任何 scalatest 匹配器

标签 json scala scalatest matcher

我的测试目前希望匹配来自被测方法的转换后的 json 字符串。我已经构建了一个预期的字符串来执行匹配。

val input = Foobar("bar", "foo")
val body = Foobar("bar !!", "foo!!")
val responseHeaders = Map[String, String]("Content-Type" -> "application/json")
val statusCode = "200"
val responseEvent = ResponseEvent(input, body, responseHeaders, statusCode)

val expected ="{\"input\":{\"foo\":\"bar\",\"bar\":\"foo\"},\"body\":{\"foo\":\"bar !!\",\"bar\":\"foo!!\"},\"headers\":{\"Content-Type\":\"application/json\"},\"statusCode\":\"200\"}"

val result = Main.stringifyResponse(responseEvent)

result should be(expected)

字符串匹配非常敏感并且在任何空格上都失败,并且测试不接受任何写在多行上的字符串,因为由于使用 json4s 库进行字符串化,结果只能在一行上使用。

有没有更好的方法来对 json 输出执行匹配,而不必使用 scalatest 进行完整的字符串比较。

有没有更好的方法来创建这个测试?

最佳答案

结帐 https://github.com/stephennancekivell/scalatest-json

libraryDependencies += "com.stephenn" %% "scalatest-json-jsonassert" % "0.0.3"
libraryDependencies += "com.stephenn" %% "scalatest-json4s" % "0.0.2"
libraryDependencies += "com.stephenn" %% "scalatest-play-json" % "0.0.1"
libraryDependencies += "com.stephenn" %% "scalatest-circe" % "0.0.1"

它让您无需关心空格即可编写测试,因为它的 json.
    it("should pass matching json with different spacing and order") {
      val input = """
        |{
        | "some": "valid json",
        | "with": ["json", "content"]
        |}
      """.stripMargin

      val expected = """
                    |{
                    | "with": ["json", "content"],
                    |     "some":   "valid json"
                    |}
                  """.stripMargin

      input should matchJson(expected)
    }

关于json - 用于匹配 json 的任何 scalatest 匹配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47765810/

相关文章:

javascript - 嵌套在 JSON 响应中的值未被解析

scala - 如果失败,如何仅显示 Scalatest 测试的标准输出

string - 字符串在ScalaTest Matchers中包含许多子字符串

scala - 初始化val可能会引发异常

testing - 你能在 scala 中测试嵌套函数吗?

java - 如何从 BindingResult 获取 Controller 中的错误文本

objective-c - 统计 JSON、NSArray

javascript - 更新图表中的数据(下拉)

java - 公共(public) Scala 构造函数字段在 Java 中不是公共(public)的

java - 如何安装 Scala IDE