Saturday, June 25, 2011

Parameterized Tests in JUnit

A parameterised test allows you to run a test against a varying set of data. If you find yourself calling the same test but with different inputs, over and over again, a parameterised test would help make your code cleaner. To create one in JUnit you need to:
  • Annotate the test class with @RunWith(Parameterized.class)
  • Create a static method annotated with @Parameters which returns a collection of arrays. Each array in the collection represents the test data and will be injected into the constructor of the test class
  • Make sure that the test class constructor matches the array items in the Parameters method and stores the test data
  • Write some test methods annotated with @Test
Example:
The example below shows a parameterised test which tests array sorting. The data method returns a collection of arrays. Each array contains an input array and an expected output (sorted) array. When you run the test, the class is instantiated with each of these arrays and then the testSort method is called.
import static org.junit.Assert.assertArrayEquals;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class ArraySortTest {

  @Parameters
  public static Collection<Object[]> data() {
      return Arrays.asList(new Object[][] {
         { new int[] { 1, 3, 2 }, new int[] { 1, 2, 3 } },
         { new int[] { 3, 2, 1 }, new int[] { 1, 2, 3 } },
         { new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 } },
         { new int[] { 1, 1, 1 }, new int[] { 1, 1, 1 } },
         { new int[] { 1 }, new int[] { 1 } },
         { new int[] {}, new int[] {} },
         });
  }

  private final int[] actual;
  private final int[] expected;

  public ArraySortTest(int[] actual, int[] expected){
      this.actual = actual;
      this.expected = expected;
  }

  @Test
  public void testSort(){
      Arrays.sort(actual);
      assertArrayEquals(expected, actual);
  }
}
Documentation
Javadocs: Class Parameterized

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.