Play Framework v 2.1 with scala,我正在尝试使用无效调用测试我的ProductController(缺少参数),我想要获得BadRequest响应..
控制器代码返回 Ok (Json.toJson(某些类..))或 BadRequest (Json.toJson(某些类...))如果出错了。
我定义了测试类:
class ProductApplicationTests extends PlaySpecification
with Mockito
with ProductServiceComponent
{
lazy val productService = mock[ProductService]
... other things
def app = FakeApplication(
withoutPlugins = Seq("com.typesafe.plugin.RedisPlugin"),
withGlobal = Some(
new GlobalSettings {
override def getControllerInstance[A](clazz: Class[A]) = clazz match {
case c if c.isAssignableFrom(classOf[ProductController]) => new ProductController(ProductApplicationTests.this).asInstanceOf[A]
case _ => super.getControllerInstance(clazz)
}
}
)
)
def mockStuff = {
productService.addProduct(any[AddProductRequest]) returns
DTOResponse(product.id.get)
productService.updateProduct(any[UpdateProductRequest]) returns
DTOResponse(product.id.get)
productService.deleteProduct(any[DeleteProductRequest]) returns
DTOResponse(product.id.get)
}
step(mockStuff)
"Application" should {
"Get product with no tenant Id" in {running(FakeApplication()) {
val req = FakeRequest(method = "POST", uri = routes.ProductController.getProducts("en_US", "1", "1").url,
headers = FakeHeaders(
Seq("Content-type"->Seq("application/json"))
),
body = None
)
val Some(result) = route(req)
status(result) must equalTo(400)
问题:
我收到错误:
Cannot write an instance of None.type to HTTP response. Try to define a Writeable[None.type]
我已经关注过这篇文章:Play 2 - Scala FakeRequest withJsonBody而且我不明白我做错了什么.. 当我发送此代码作为测试时,它可以工作..
"Get product with valid parameters" in new WithApplication(app) {
val result = route(FakeRequest(GET, "/v1.0/products?lang=en_US&t=1&ids=1,2"))
result must beSome
status(result.get) must equalTo(OK)
contentType(result.get) must beSome.which(_ == "application/json")
contentAsString(result.get) must contain("products")
contentAsString(result.get) must contain("notFoundIds")
}
感谢您的任何评论/答案..
顺便说一句,我的global.scala看起来像:
override def onBadRequest(request: RequestHeader, error: String) = {
var errorResponse:ErrorResponse[String] = ErrorResponse(ErrorCode.GeneralError, "Error processing request", 500)
errorResponse.addMessage(error)
Future.successful(BadRequest(Json.toJson(errorResponse)))
}
override def onError(request: RequestHeader, ex: Throwable) =
{
var errorResponse:ErrorResponse[String] = ErrorResponse(ErrorCode.GeneralError, "Error processing request", 500)
errorResponse.addMessage(ex.getMessage)
Future.successful(BadRequest(Json.toJson(errorResponse)))
}
如果我在RestAPI测试客户端运行Get,我得到:
{"code":100,"message":"Error processing request - Missing parameter: t"}
答案 0 :(得分:0)
如果你看一下source for FakeRequest,你会注意到你需要将正文设置为AnyContentAsEmpty
。在旁注中,第一种测试方法应该是POST吗?你的其他例子似乎是GET。
至于你在RestAPI tet客户端运行Get的第二个问题,错误信息似乎很清楚,你需要提供参数t,就像你在上一个例子中所做的那样val result = route(FakeRequest(GET, "/v1.0/products?lang=en_US&t=1&ids=1,2"))