Test your application

Creating automatic test suites for your application is a good way to make it robust. It allows you to work in a very agile way.

Play! tests are built using JUnit 4. Test classes construction is very standard, but the test classes must be created in the application package of the test/ directory. Most of time they will extends the play.test.ApplicationTest support class.

package application;

import static org.junit.Assert.*;
import org.junit.Test;
import play.test.ApplicationTest;

public class SomeTests extends ApplicationTest {
    
    @Test
    public void fakeTest() {
        assertEquals(2, 1+1); // A really important thing to test
    }

}

To launch the test suite for an application, use the play test command.

# play test

When you run tests this way, Play! will start with a special test framework ID. So you can define special configurations in the application.conf file.

For example :

%test.db=mem
%test.jpa.ddl=create-drop

How to test things

Simulating HTTP requests

Play! allow you to test your application from a client point.

You can simulate HTTP requests by submitting directly play.mvc.Http.Request objects without the need to manage the network. You get back the generated play.mvc.Http.Response, and if exceptions are thrown, you get it directly.

@Test
public void getJsonProduct() {
    Response response = GET("/products/1124.json");
    assertStatus(200, response);
    assertContentType("text/json", response);
    assertContentEquals("{id:1124}", response);
}

Testing the router

You can test the Router to verify that your routes definitions are correct.

@Test
public void checkRoutes() {
    Map<String,String> mapping = Router.route("GET", "/products/12124");
    assertEquals("Products.show", mapping.get("action"));
    assertEquals("12124", mapping.get("id"));
    assertNull(Router.route("POST", "/products/12124"));

    // Test reverse generation
    assertEquals("GET /", Router.reverse("Products.index"));
}

Testing a template

You can test directly template rendering, but you have to submit yourself the correct template binding. So it's generally only usefull to test independent templates like email templates.

@Test
public void testTemplate() {
    Template template = TemplateLoader.load("confirmation_email.txt");
    Map<String,Object> binding = new HashMap<String, Object>();
    binding.put("user", new User("guillaume"));
    String email = template.render(binding);
    assertEquals("Welcome guillaume !", email);
}

Testing your model object

You can test directly internal components of the application like your model object domain. Play! will then prepare artefact's like open a database connection or prepare a JPA transaction.

@Test
public void testProducts() {
    Product p = new Product("Test", 58);
    p.save();
    assertEquals(1, Product.findAll().size());
}
Page infos : contents/test.txt · Last modified: 2008/12/03 18:52 by gbo
Show pagesource - Old revisions - Backlinks -