Sunday, 27 December 2015

BeforeClass in Parameterized JUnit Test

Recently I was faced with an old problem again: JUnit does not run the @BeforeClass method before the @Parameters method. So I had to apply a workaround – to call the initialisation method within the parameters method.
@RunWith(Parameterized.class)
public class TestAddress2 {
 static Address addr, addr2, addr3;
 ...
 // for parameterized tests
 private Boolean equalResult, identicalResult;
 private Address a1, a2;

 //@BeforeClass
 public static  void init() {
  // set up addr, addr2, addr3
 }
 public TestAddress2(Boolean eqResult, Boolean idResult, Address a1, Address a2) {
  this.equalResult=eqResult;
  this.identicalResult=idResult;
  this.a1=a1;
  this.a2=a2;
 }
 @Parameters
 public static Collection parameters() {
  init();
  // equalResult, identicalResult, address 1, address 2
  return Arrays.asList(new Object[][] {
   { false, true, addr, addr3 },
   { false, false, addr, addr2 },
   { false, true, addr3, addr },
   { false, false, addr2, addr3 },
   { false, false, addr3, addr2 },
  });
 }
 @Test
 public void testEquals() {
  assertEquals(equalResult, a1.equals(a2));
 }
 @Test
 public void testIdentical() {
  assertEquals(identicalResult, a1.identical(a2));
 }
}

No comments: