15.1. Data-Driven Tests in JUnit

In JUnit 4, you can use the Parameterized test runner to perform data-driven tests. In Thucydides, you use the ThucydidesParameterizedRunner. This runner is very similar to the JUnit Parameterized test runner, except that you use the TestData annotation to provide test data, and you can use all of the other Thucydides annotations (@Managed, @ManagedPages, @Steps and so on). This test runner will also generate proper Thucydides HTML and XML reports for the executed tests.

An example of a data-driven Thucydides test is shown below. In this test, we are checking that valid ages and favorite colors are accepted by the sign-on page of an (imaginary) application. To test this, we use several combinations of ages and favorite colors, specified by the testData() method. These values are represented as instance variables in the test class, and instantiated via the constructor.

@RunWith(ThucydidesParameterizedRunner.class)
public class WhenEnteringPersonalDetails {

    @TestData
    public static Collection<Object[]> testData() {
        return Arrays.asList(new Object[][]{
                {25, "Red"},
                {40, "Blue"},
                {36, "Green"},
        });
    }

    @Managed
    public WebDriver webdriver;

    @ManagedPages(defaultUrl = "http://www.myapp.com")
    public Pages pages;

    @Steps
    public SignupSteps signup;

    private Integer age;
    private String favoriteColor;

    public WhenEnteringPersonalDetails(Integer age, String favoriteColor) {
        this.age = age;
        this.favoriteColor = favoriteColor;
    }

    @Test
    public void valid_personal_details_should_be_accepted() {
        signup.navigateToPersonalDetailsPage();
        signup.enterPersonalDetails(age, favoriteColor);
    }
}