Documentation

You are viewing the documentation for the 2.0.1 release in the 2.0.x series of releases. The latest stable release series is 3.0.x.

§Writing functional tests

§Testing a template

Since a template is a standard Scala function, you can execute it from your test, and check the result:

"render index template" in {
  val html = views.html.index("Coco")
  
  contentType(html) must equalTo("text/html")
  contentAsString(html) must contain("Hello Coco")
}

§Testing your controllers

You can call any Action code by providing a FakeRequest:

"respond to the index Action" in {
  val result = controllers.Application.index("Bob")(FakeRequest())
  
  status(result) must equalTo(OK)
  contentType(result) must beSome("text/html")
  charset(result) must beSome("utf-8")
  contentAsString(result) must contain("Hello Bob")
}

§Testing the router

Instead of calling the Action yourself, you can let the Router do it:

"respond to the index Action" in {
  val Some(result) = routeAndCall(FakeRequest(GET, "/Bob"))
  
  status(result) must equalTo(OK)
  contentType(result) must beSome("text/html")
  charset(result) must beSome("utf-8")
  contentAsString(result) must contain("Hello Bob")
}

§Starting a real HTTP server

Sometimes you want to test the real HTTP stack from with your test, in which case you can start a test server:

"run in a server" in {
  running(TestServer(3333)) {
  
    await(WS.url("http://localhost:3333").get).status must equalTo(OK)
  
  }
}

§Testing from within a Web browser.

If you want to test your application using a browser, you can use Selenium WebDriver. Play will start the WebDriver for your, and wrap it in the convenient API provided by FluentLenium.

"run in a browser" in {
  running(TestServer(3333), HTMLUNIT) { browser =>
    
    browser.goTo("http://localhost:3333")
    browser.$("#title").getTexts().get(0) must equalTo("Hello Guest")
    
    browser.$("a").click()
    
    browser.url must equalTo("http://localhost:3333/Coco")
    browser.$("#title").getTexts().get(0) must equalTo("Hello Coco")

  }
}

Next: Advanced topics