json - 如何将 json 中的顶级数组与 specs2 匹配

标签 json scala specs2

在 specs2 中,你可以为这样的元素匹配一个数组:

val json = """{"products":[{"name":"shirt","price":10, "ids":["1", "2", "3"]},{"name":"shoe","price":5}]}"""

def aProductWith(name: Matcher[JsonType],  price: Matcher[JsonType]): Matcher[String] =
  /("name").andHave(name) and /("price").andHave(price)

def haveProducts(products: Matcher[String]*): Matcher[String] =
  /("products").andHave(allOf(products:_*))

json must haveProducts(
  aProductWith(name = "shirt", price = 10) and /("ids").andHave(exactly("1", "2", "3")),
  aProductWith(name = "shoe", price = 5)
)

(示例取自此处:http://etorreborre.github.io/specs2/guide/SPECS2-3.0/org.specs2.guide.Matchers.html)

如果 products 是 json 中的根元素,我该如何做同样的事情,即匹配产品的内容? haveProducts 应该是什么样子?

val json = """[{"name":"shirt","price":10, "ids":["1", "2", "3"]},{"name":"shoe","price":5}]"""

最佳答案

你可以像这样用 have(allOf(products:_*)) 替换 /("products").andHave(allOf(products:_*)) :

val json = """[{"name":"shirt","price":10, "ids":["1", "2", "3"]},{"name":"shoe","price":5}]"""

def aProductWith(name: Matcher[JsonType],  price: Matcher[JsonType]): Matcher[String] =
  /("name").andHave(name) and /("price").andHave(price)

def haveProducts(products: Matcher[String]*): Matcher[String] = have(allOf(products:_*))

json must haveProducts(
  aProductWith(name = "shirt", price = 10) and /("ids").andHave(exactly("1", "2", "3")),
  aProductWith(name = "shoe", price = 5)
)

关于json - 如何将 json 中的顶级数组与 specs2 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32177466/

相关文章:

c++ - 从 Qt 中的 Web 服务解析未命名的 JSON 数组

json - .net core 3 在 AddJsonOptions 中没有 ReferenceLoopHandling

scala - 是否有任何插件可以为 Play 2.x 生成 API 文档?

mongodb - 使用子类检索 Salat 对象时出现异常

scala - Spray.io升级导致specs2中缺少模拟库

javascript - 如何JSON解析多元素数组?

json - 复制 json 文件时出现 Amazon Redshift 错误 - 无效的 JSONPath 格式 : Member is not an object

scala - Scala 中 -_ 是什么意思?

使用 Scala 进行安卓开发

scala - specs2 验收测试中的案例类上下文 : "must is not a member of Int"