Playframework(18)RESTFul and Testing/Logging

本文介绍了一个基于Playframework的RESTful API实现,并使用Specs2进行了详细的单元测试。主要内容包括控制器的定义、JSON数据交互及不同HTTP方法的处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值