Community contributed extensions

springtester

The springtester module is used in conjunction with the spring module. Internally, it uses the Mockito library and provides additional classes for injecting mocks/stubs when writing tests for your Play! application.

Getting started

Include springtester in your Play! application by adding the following in your dependencies.yml:

- play -> springtester [version]

As springtester depends on the existing Spring Play! module, you will have to include it as well:

- play -> spring [version]

Note: springtester has currently only been tested with version 1.0.1 of the spring module.

Then update your project’s dependencies to include springtester and its dependencies:

play deps

Usage

The springtester module assumes you are wiring your application using the spring module. Here is an example of two classes being wired up using the spring module. The first is a Person class that injects an AgeCalculator and calls the calculate(...) method:

@Component
public class Person {
    // Here we are injecting the AgeCalculator into the Person class
    @Resource private AgeCalculator ageCalculator;
    public boolean canVote() {
        int age = calculator.calculate("1-January-1980");
        return age >= 18;
    }
}

Note that person itself is annotated with the Component annotation. The AgeCalculator will then take birth date of the Person and calculate their age:

@Component
public class AgeCalculator {
    public int calculate(String birthDate) {
        // some code that figures out the age of the person
    }
}

Now let’s say you want to write a test for Person called PersonTest and wish to replace the AgeCalculator with a mock that returns the age of 20 instead of calculating the actual age of the Person:

public final class PersonTest extends SpringMockitoUnitTestCase {
    @Subject private Person subject;
    @Mock(name = "ageCalculator") AgeCalculator mockAgeCalculator;
    @Test
    public void testCanVote() throws Exception {
        Mockito.when(mockAgeCalculator.calculate("1-January-1980")).thenReturn(20);
        boolean actual = subject.canVote();
        assertEquals(true, actual);
    }
}

How it works:

// The name of the mock "ageCalculator" has the same name as the
// field "ageCalculator" found in the Person class and therefore
// does not require the "name" property.
@Mock AgeCalculator ageCalculator;