Repetitive testcases with jUnit


49134136_bd08741bf9_b
Update: after listening to a recent episode of Java Posse, I found out about parameterized tests for JUnit which seems to be a better option than the method described below. Live and learn.

Let’s say you have a lot of similar cases in a jUnit test. You might be tempted to write a loop to factor out the commonalities. Take the following (trivial) example:

public class TestUnitTest {
  @Test
  public void testMultiple() throws Exception {
    Integer cases[][] = {
      {1, 2, 3},
      {2, 3, 6},
      {1, 1, 2},
      {3, 0, 3},
    };
    
    for (Integer[] c : cases)     
      assertEquals((Integer)(c[0] + c[1]), c[2]);
  }
}

The problem is that the exception will be always at the same line. I found that it is easier to factor out the functionality into a method and call that method repeatedly:

public class TestUnitTest { 
  private int sum(int a, int b) {
    return a + b;
  }
  
  @Test
  public void testLineByLine() throws Exception {
    assertEquals(sum(1, 2), 3);
    assertEquals(sum(2, 3), 6);
    assertEquals(sum(1, 1), 2);
    assertEquals(sum(3, 0), 3);
  }
}

This way you will see in your stacktrace which subcase failed exactly.

Picture taken from psd’s photostream with permission.

,

Leave a Reply

Your email address will not be published. Required fields are marked *