我正在使用 Play !框架并尝试在 Specs2 测试中处理 JSON 响应消息,但没有成功。
我想要做的是在 JsValue 中断言键-> 值对,如下例所示......但我无法让匹配器正确通过。
import org.specs2.mutable._
import play.api.libs.json.{Json, JsValue}
class JsonSpec extends Specification {
"Json Matcher" should {
"Correctly match Name->Value pairs" in {
val resultJson:JsValue = Json.parse("""{"name":"Yardies"}""")
resultJson must /("name" -> "Yardies")
}
"Correctly match Name->Value pairs with numbers as doubles" in {
val resultJson:JsValue = Json.parse("""{"id":1}""")
resultJson must /("id" -> 1.0)
}
}
}
我得到的错误是
{name : Yardies} doesn't contain '(name,Yardies)'
和
{id : 1.0} doesn't contain '(id,1.0)'
不是很有帮助,我想这是我遗漏的一些简单的东西(Scala 和 Play 都是新的)
史蒂夫
最佳答案
JsonMatchers
在 specs2 中应该收紧一点。他们是 Matcher[Any]
,其中 Any
应该有一个 toString
可以由 Scala 的 json 解析器(而不是 Play 的解析器)解析的方法。
以下规范按预期工作:
class JsonSpec extends Specification {
"Json Matcher" should {
"Correctly match Name->Value pairs" in {
val resultJson = """{"name":"Yardies"}"""
resultJson must /("name" -> "Yardies")
}
"Correctly match Name->Value pairs with numbers as doubles" in {
val resultJson = """{"id":1}"""
resultJson must /("id" -> 1.0)
}
}
}
在你的情况下,我怀疑解析
toString
Play 的 Json 值的表示返回的内容与匹配器所期望的略有不同。这将在下一个规范 2 版本中修复。
关于json - Playframework Scala Specs2 JSON 匹配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15694461/