Unit Testing a Play framework Controller

2.7k views Asked by At

I have written this controller which works perfectly from browser

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))
  }
}

The route is defined as

GET     /listProducts.xml              controllers.Application.listProductsXML

Now I am writing a unit test for this controller

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")
        }
    }
}

When I run this with activator test-only I get an error

[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

There are 1 answers

0
bjfletcher On BEST ANSWER

Try replacing:

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

with:

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

Pre Play 2.4, the controllers used to be objects. From Play 2.4 on, it's encouraged for them to be classes instead.