单元测试Play框架控制器

时间:2015-06-19 21:59:56

标签: scala playframework specs2

我已经编写了这个控制器,可以从浏览器中完美运行

package controllers
import play.api._
import play.api.mvc._

class Application extends Controller {

  val productMap = Map(1 -> "Keyboard", 2 -> "Mouse", 3 -> "Monitor")

  def listProductsXML() = Action {
    Ok(views.xml.products(productMap))
  }
}

路线定义为

GET     /listProducts.xml              controllers.Application.listProductsXML

现在我正在为这个控制器编写单元测试

import controllers._
import play.api.test.FakeRequest
import play.api.test.Helpers._
import org.specs2.mutable._
import play.api.test.WithApplication

class ControllerTest extends Specification {
    "controllers.Application" should {
        "respond with xml for /listproducts.xml requests" in new WithApplication {
            val result = controllers.Application.listProductsXML()(FakeRequest())
            status(result) must equalTo(OK)
            contentType(result) must beSome("application/xml")
            contentAsString(result) must contain("products")
        }
    }
}

当我使用activator test-only运行时出现错误

[foo_play] $ test-only ControllerTest
[error] ProductSpec.scala:10: object Application is not a member of package controllers
[error] Note: class Application exists, but it has no companion object.
[error]             val result = controllers.Application.listproductsXML()(FakeRequest())
[error]                                      ^
[error] one error found
[error] (test:compileIncremental) Compilation failed
[error] Total time: 1 s, completed Jun 19, 2015 3:48:14 PM

1 个答案:

答案 0 :(得分:3)

尝试更换:

controllers.Application.listProductsXML()(FakeRequest())

使用:

new controllers.Application().listProductsXML()(FakeRequest())

Pre Play 2.4,控制器曾经是对象。从Play 2.4开始,鼓励他们成为课程。