2015-10-29 81 views

回答

2

這是一個可能性

控制器

@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)) 

    } 
    } 
} 

但願這給你什麼,你可以測試或你可能想要做什麼了。