使用 Play-Json 和 Specs2,我可以像这样匹配 json-body:
contentAsJson(res) must equalTo(responseBody)
是否有可能忽略 json-arrays 的顺序(递归),而是像对待集合一样对待 json-arrays 的相等性?
使用 Play-Json 和 Specs2,我可以像这样匹配 json-body:
contentAsJson(res) must equalTo(responseBody)
是否有可能忽略 json-arrays 的顺序(递归),而是像对待集合一样对待 json-arrays 的相等性?
涉及到一些工作,这取决于您希望失败消息有多好。你可以做这样的事情
import org.specs2._
import execute._
import matcher._
import play.api.libs.json._
trait JsValueMatchers extends MustMatchers {
def beEqualj(expected: JsValue): Matcher[JsValue] = { actual: JsValue =>
(actual, expected) match {
case (JsArray(as), JsArray(es)) =>
asPair(as must contain(allOf(es.map(beEqualj):_*)).exactly)
case (JsObject(as), JsObject(es)) =>
asPair(as must contain(allOf(es.toList.map(pairEqualj):_*)).exactly.inOrder)
case (JsNull, JsNull) =>
(true, "ko")
case (JsBoolean(a), JsBoolean(e)) =>
(a == e, s"ko: $a is not equal to $e")
case (JsString(a), JsString(e)) =>
(a == e, s"ko: $a is not equal to $e")
case (JsNumber(a), JsNumber(e)) =>
(a == e, s"ko: $a is not equal to $e")
case _ =>
(false, s"$actual and $expected don't have the same type")
}
}
def pairEqualj(expected: (String, JsValue)): Matcher[(String, JsValue)] = { actual: (String, JsValue) =>
val (key, value) = actual
val result = (key must_== expected._1) and
(value must beEqualj(expected._2))
asPair(result)
}
def asPair[R : AsResult](r: R): (Boolean, String) = {
val result = AsResult(r)
(result.isSuccess, result.message)
}
}
object JsValueMatchers
您可以将 json 转换为案例类并将它们作为集合进行比较:
contentAsJson(res).as[Set[User]] must equalTo(Json.parse(responseBody).as[Set[User]])