I often write tests when I need to set data object for integration tests involving a few pages with forms. Herein each form on a page could be represented by a different data object class. There are are times when test end up in filling same data for a specific page while varying it for other pages and validating the overall flow. I thought instead of setting data object each time from test method I can take advantage of instance initialization block to set data for tests. Herein I have listed a smaller version of tests I usually write -
This my data class which holds data for form values - textbox, drop down etc. I have not kept setters for sake of brevity -
public class DataClass {
private int i;
private int j;
public DataClass() {
i=1;
j=1;
}
public int getI(){
return i;
}
public int getJ(){
return j;
}
}
Following is the helper class which is used by test class to fill form data on page -
public class WorkerClass {
private DataClass data;
public void setData(DataClass data){
this.data = data;
}
public int add() {
return data.getI()+data.getJ();
}
public int substract() {
return data.getI()-data.getJ();
}
}
And here is the test method. Notice that instead of calling setData of WorkerClass in each test method I used instance initialization block -
public class TestClass {
private DataClass data = new DataClass();
WorkerClass workerClass = new WorkerClass();
{
workerClass.setData(data);
}
@Test
public void testAddition() {
assert workerClass.add()==0:"addition Failed";
}
@Test
public void testSubstraction() {
assert workerClass.substract()==0:"substraction failed";
}
}
My question is, am I misusing instance initialization block and should rather be calling it from each test method, even if all the test method require same set of data?