Testing your Play! controllers

DZone 's Guide to

Testing your Play! controllers

· Java Zone ·
Free Resource
Lets say you have a controller like this (from the Play! documentation)

package controllers;
import java.util.*;
import play.*;
import play.mvc.*;
import models.*;
public class Application extends Controller {
    public static void index() {
        Post frontPost = Post.find("order by postedAt desc").first();
        List<post> olderPosts = Post.find(
            "order by postedAt desc"
        render(frontPost, olderPosts);

And you want to write a test to check the render parameters are correct, how do you do that?

Well here is a little example
public class ApplicationTest extends FunctionalTest{
 public void before() {
 public void testHomePageFirstPost() throws MalformedURLException {
  // Call the home page
  Response response = GET("/");
  // Verify that Matches.matchCreate() passed correct params to render().
  Post frontPost = (Post) getRenderParameter("frontPost");
  assertEquals(${value_from_yml}, frontPost.author.fullname);
  assertEquals(${value_from_yml}, frontPost.postedAt);
  * Gets the parameter that was passed to render() method.
  * @param key
  * @return
 public static Object getRenderParameter(String key) {
  RenderArgs current = Scope.RenderArgs.current();
  return current.data.get(key);

You might want to put the getRenderParameter in a separate class to easily reuse it.

If you want to test a controller method that take parameters is as easy.

Let's assume you want to test a simple controller method in Users called getUserByUsername to make sure the correct user is added to render when the form is submitted

public class Users extends Controller {
 * Gets the user given his username
    public static void getUserByUsername(String username) {
        User currentUser = User.find("byUsername", username).first();

In this case the test would be

public class UserLoginTest extends FunctionalTest{
 public void before() {
 public void testGetByUsername() {
  Map<String, String> params = new HashMap<String, String>();
  params.put("username", "user1");
  Response response = POST("/users/getbyusername", params, new HashMap<String, File>());
  User currentUser = (User) getRenderParameter("currentUser");
  assertEquals(${from_users.yml}, currentUser.name);
  assertEquals(${from_users.yml}, currentUser.email);

Please feel free to comment!
From http://www.devinprogress.info/2011/03/unit-test-your-play-controllers.html

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}