Playframework(18)RESTFul and Testing/Logging

Playframework(18)RESTFulandTesting/Logging

Finally,IdecidetouseSpecs2totestallmythings.ImayneedtoreadmoredetailifIusethis.

TestingtheController

packagecontrollers

importplay.api.libs.json._

importplay.api.mvc._

importmodels.Book

traitBookController{

this:Controller=>

deflistBooks=Action{

Ok(Json.toJson(Book.books))

}

defsaveBook=Action(BodyParsers.parse.json){request=>

valb=request.body.validate[Book]

b.fold(

errors=>{

BadRequest(Json.obj("status"->"OK","message"->JsError.toFlatJson(errors)))

},

book=>{

Book.addBook(book)

Ok(Json.obj("status"->"OK"))

}

)

}

defgetBook(id:String)=Action{

Book.getBook(id)match{

caseSome(b)=>Ok(Json.toJson(b))

case_=>Ok(Json.obj("status"->"OK","message"->"BookNotFound!"))

}

}

defdeleteBook(id:String)=Action{

Book.deleteBook(id)

Ok(Json.obj("status"->"OK"))

}

defupdateBook(id:String)=Action(BodyParsers.parse.json){request=>

valb=request.body.validate[Book]

b.fold(

errors=>{

BadRequest(Json.obj("status"->"OK","message"->JsError.toFlatJson(errors)))

},

book=>{

book.id=Some(id)

Book.updateBook(book)

Ok(Json.obj("status"->"OK"))

}

)

}

}

objectBookControllerextendsControllerwithBookController

packagecontrollers

importplay.api.libs.json.JsValue

importplay.api.mvc._

importplay.api.test._

importscala.concurrent.Future

/**

*Createdbycarlon9/9/15.

*/

classBookControllerSpecextendsPlaySpecificationwithResults{

classTestController()extendsControllerwithBookController

"BookAPI#listBooks"should{

"sizeshouldbe2"in{

valcontroller=newTestController

valresult:Future[Result]=controller.listBooks.apply(FakeRequest())

valbodyText:JsValue=contentAsJson(result)

bodyTextmustnotbenull

}

}

}

Thiscommandwilldothework

>sbt"testOnlymodels.*"

References:

https://github.com/faubertin/scala-play-rest-example

https://www.playframework.com/documentation/2.4.x/ScalaHome

https://www.playframework.com/documentation/2.4.x/ScalaTestingWithSpecs2

https://www.playframework.com/documentation/2.4.x/ScalaFunctionalTestingWithSpecs2

相关推荐