Thursday, March 3, 2011

Parameterized Unit Tests

Recently, I have to write a unit test to check link reference validity in static HTML pages. The problem is: how to run test for each URL, without hard coded HTML files location (what append if several files are added ;) and with a minimum of code. The answer is provided by JUnit itself. From version 4, parameterized tests are included: it is a runner that is able to get a collection of values and to execute a test for each of these values.

A parameterized test looks as following:

@RunWith(Parameterized.class)
public class ParamTest {

private String msg;

public ParamTest(String msg) {
this.msg = msg;
}

@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {{"first"}, {"second"}, {"third"}});
}

@Test
public void test(){
System.out.println(msg);
}

}

To get a parameterized test, it has to declare a specific runner with: @RunWith(Parameterized.class). And a static method that return a Collection<Object[]>. By this way, several arguments can be passed. This method must be annotated with @Parameters that declares the method as a parameters provider. A constructor with all arguments as parameters must be written. Then runner will execute the parameters method provider, and for each value, it creates an instance of the test and execute it. So, to use parameters, the constructor can save them as class attributes.

The result is:

first
second
third

Parameterized tests mechanism brings a simple and ellegant way to test things that are not fix.