Skip to content
wsargent edited this page Jul 13, 2012 · 12 revisions

Testing your application

Test source files must be placed in your application’s test folder. You can run them from the Play console using the ``test(run all tests) andtest-only` (run one test class: `test-only my.namespace.MySpec`) tasks.

Using specs2

The default way to test a Play 2 application is by using specs2.

Unit specifications extend the org.specs2.mutable.Specification trait and are using the should/in format:

import org.specs2.mutable._

import play.api.test._
import play.api.test.Helpers._

class HelloWorldSpec extends Specification {

  "The 'Hello world' string" should {
    "contain 11 characters" in {
      "Hello world" must have size(11)
    }
    "start with 'Hello'" in {
      "Hello world" must startWith("Hello")
    }
    "end with 'world'" in {
      "Hello world" must endWith("world")
    }
  }
}

Running in a fake application

If the code you want to test depends on a running application, you can easily create a FakeApplication on the fly:

"Computer model" should {

  "be retrieved by id" in {
    running(FakeApplication()) {
  
      val Some(macintosh) = Computer.findById(21)

      macintosh.name must equalTo("Macintosh")
      macintosh.introduced must beSome.which(dateIs(_, "1984-01-24"))  
  
    }
  }
}

You can also pass (or override) additional configuration to the fake application, or mock any plug-in. For example to create a FakeApplication using a default in memory database:

FakeApplication(additionalConfiguration = inMemoryDatabase())

Unit Testing Controllers

Controllers are defined as objects in Play, and so can be trickier to unit test. One way to finesse unit testing with a controller is to use a trait with an explicitly typed self reference to the controller:

trait ExampleController {
  this: Controller =>

  def index() = {
     ...
  }
}

object ExampleController extends Controller with ExampleController

and then test the trait:

object ExampleControllerSpec extends Specification {

  class TestController() extends Controller with ExampleController

  "Example Page#index" should {
    "should be valid" in {
          val controller = new TestController()          
          val result = controller.index()          
          result must not beNull
      }
    }
  }
}

This approach can be extended with your choice of dependency injection framework (Subcut/Spring/Guice/Cake Pattern) to set up and inject mocks into the trait.

Next: Writing functional tests

Clone this wiki locally