Playframework(18)RESTFul and Testing/Logging
Finally, I decide to use Specs2 to test all my things. I may need to read more detail if I use this.
Testing the Controller
package controllers
import play.api.libs.json._
import play.api.mvc._
import models.Book
trait BookController {
this: Controller =>
def listBooks = Action {
Ok(Json.toJson(Book.books))
}
def saveBook = Action(BodyParsers.parse.json) { request =>
val b = 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"))
}
)
}
def getBook(id:String) = Action {
Book.getBook(id) match {
case Some(b) => Ok(Json.toJson(b))
case _ => Ok(Json.obj("status" -> "OK", "message" -> "Book Not Found!"))
}
}
def deleteBook(id:String) = Action {
Book.deleteBook(id)
Ok(Json.obj("status" -> "OK"))
}
def updateBook(id:String) = Action(BodyParsers.parse.json){ request =>
val b = 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"))
}
)
}
}
object BookController extends Controller with BookController
package controllers
import play.api.libs.json.JsValue
import play.api.mvc._
import play.api.test._
import scala.concurrent.Future
/**
* Created by carl on 9/9/15.
*/
class BookControllerSpec extends PlaySpecification with Results{
class TestController() extends Controller with BookController
"Book API#listBooks" should {
"size should be 2" in {
val controller = new TestController
val result: Future[Result] = controller.listBooks.apply(FakeRequest())
val bodyText: JsValue = contentAsJson(result)
bodyText must not be null
}
}
}
This command will do the work
> sbt "testOnly models.*"
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
Playframework(18)RESTFul and Testing/Logging
猜你喜欢
转载自sillycat.iteye.com/blog/2242284
今日推荐
周排行