I\'m using JUnit 4. I can\'t see the difference between initializing in the constructor or using a dedicated init function annotated by @Before
. Does this mean
There is one thing that constructor can archive but not @Before.
You have to use a constructor when you need to initial fields defined in parent class. For example:
abstract class AbstractIT {
int fieldAssignedInSubClass;
public AbstractIT(int fieldAssignedInSubClass) {
this.fieldAssignedInSubClass= fieldAssignedInSubClass;
}
@Before
void before() {
// comsume fieldAssignedInSubClass
}
}
public class ChildIT extends AbstractIT{
public ChildIT() {
// assign fieldAssignedInSubClass by constructor
super(5566);
}
@Before
void before() {
// you cannot assign fieldAssignedInSubClass by a @Before method
}
}