【问题标题】:Specs2 JSONMatchers: mapping over Array elements?Specs2 JSONMatchers:映射数组元素?
【发布时间】:2014-01-28 20:11:19
【问题描述】:

我正在使用 Specs2 JSONMatcher 来验证 GET 请求是否已从其内部表示正确转换(在生成 JSON 之前我们会进行一些操作)。我需要做的是,确保 JSON 数组中的元素与我们存储库中的相应对象匹配。

我尝试过的:

val response = response.entity.asString // Spray's way of getting the JSON response
repository.all.map { obj =>
  resp must */ ("id" -> obj.id)
  resp must */ ("state" -> generateState(obj)
}

问题在于 */ 匹配器只是发现“state”:“whatever”(假设 generateState 返回“whatever”)存在于 JSON 文档中的某处,不一定与 ID 匹配的同一个中

我尝试使用索引,但 repository.all 方法并不总是以相同的顺序返回元素,因此无法通过索引进行匹配。

我想做的是,遍历 JSON 数组的元素并分别匹配每个元素。说一个为每个元素获取匹配器的 /## 运算符(或其他东西):

resp /## { elem =>
  val id = elem("id")
  val obj = repository.lookup(id)
  elem /("state" -> generateState(obj))
}

有没有人有办法做到这一点或类似的事情?

【问题讨论】:

    标签: scala specs2


    【解决方案1】:

    可能目前最简单的事情(直到对JsonMatchers 进行严重重构)是进行一些解析并在Matcher[String] 中递归使用JsonMatchers

    """{'db' : { 'id' : '1', 'state' : 'ok_1'} }""" must /("db" -> stateIsOk)
    
    // a string matcher for the json string in 'db'
    def stateIsOk: Matcher[String] = { json: String =>
      // you need to provide a way to access the 'id' field
      // then you can go on using a json matcher for the state
      findId(json) must beSome { id: String =>
        val obj = repository.lookup(id)
        json must /("state" -> generate(obj))
      }
    }
    
    // I am using my own parse function here
    def findId(json: String): Option[String] = 
      parse(json).flatMap { a => 
        findDeep("id", a).collect { case JSONArray(List(v)) => v.toString }
      }
    
    // dummy system
    def generate(id: String) = "ok_"+id
    
    case object repository {
      def lookup(id: String) = id
    }
    

    【讨论】:

      【解决方案2】:

      我最后做的是使用responseAs[JArray]JArray#arrJObject#values将JSON结构转换为Lists和Maps,然后使用标准的ListMap匹配器。更加灵活。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-04
        • 2020-12-24
        • 2014-03-04
        • 2018-04-22
        • 2017-07-03
        • 2022-10-06
        • 2022-01-02
        • 1970-01-01
        相关资源
        最近更新 更多