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));
 }
}

3 comments:

prashanth said...

wonderful information.
very useful informative article.
keep sharing.

reema said...

Amazing Article. Thank you for providing this useful information for students.
software developers in amritsar

ONLEI Technologies said...

Very Nice Blog . Thanks for Posting
I found this post really interesting. This information is beneficial for those who are looking for
Python Training in Noida
Machine Learning Training in Noida
Data Science Training in Noida
Digital Marketing Training in Noida
Data Analytics Training in Noida