测试响应是JsonArray-Play框架2.4.2规范2测试



我正在尝试使用Play 2.4.2,Spec 2,测试bellow

" test response Returns a json  Array" in new WithApplication {
  val response = route(FakeRequest(GET, "/myservice/xx")).get
  // ??? test response is a json array
}

测试这种情况的方法是什么?

以下是的可能性

控制器

  @Singleton 
  class BarryController extends Controller{
     def barry = Action { implicit request =>
     val json: JsValue = Json.parse("""
      {
       "residents" : [ {
         "name" : "Fiver",
         "age" : 4,
         "role" : null
       }, {
        "name" : "Bigwig",
        "age" : 6,
        "role" : "Owsla"
      } ]
        }
         """)
  Ok(json)
  }
}

测试

import org.specs2.mutable._
import play.api.mvc._
import play.api.test.FakeRequest
import play.api.test.Helpers._
import play.api.test.WithApplication
import controllers._
import play.api.libs.json._

class BarryControllerSpec extends Specification {
  "controllers.BarryController" should {
      val expectedJson: JsValue = Json.parse("""
          {
            "residents" : [ {
              "name" : "Fiver",
              "age" : 4,
              "role" : null
            }, {
              "name" : "Bigwig",
              "age" : 6,
              "role" : "Owsla"
            } ]
          }
          """)
     "respond with JsArray for /barry" in new WithApplication {
       val result = new controllers.BarryController().barry()(FakeRequest())
       status(result) must equalTo(OK)
       contentType(result) must equalTo(Some("application/json"))
       //testing class is JsArray. The .get is necessary to get type out of JsLookupResult/JsDefined instance
       (contentAsJson(result)  "residents").get must haveClass[JsArray]
       //testing JSON is equal to expected
       contentAsJson(result) must equalTo(expectedJson)
       //test an attribute in JSON
       val residents = (contentAsJson(result)  "residents").get
       (residents(0)  "age").get must equalTo(JsNumber(4))
     }
  }
}

希望这能给你一些关于你可以测试什么或你可能想做什么的想法。

相关内容

  • 没有找到相关文章

最新更新