I'm trying to test bellow using Play 2.4.2 , Spec 2 ,
" test response Returns a json Array" in new WithApplication {
val response = route(FakeRequest(GET, "/myservice/xx")).get
// ??? test response is a json array
}
What would be the way to test this scenario ?
Here is a possibility
Controller
@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)
}
}
Test
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))
}
}
}
Hopefully this gives you some ideas on what you can test or what you might want to do.