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 that I don’t have to worry about it?
Is there any case when @Before gives more than just initializing in the constructor?
No, using the constructor to initialize your JUnit test fixture is technically equal to using the
@Beforemethod (due to the fact that JUnit creates a new instance of the testing class for each@Test). The only (connotational) difference is that it breaks the symmetry between@Beforeand@After, which may be confusing for some. IMHO it is better to adhere to conventions (which is using@Before).Note also that prior to JUnit 4 and annotations, there were dedicated
setUp()andtearDown()methods – the@Beforeand@Afterannotations replace these, but preserve the underlying logic. So using the annotations also makes life easier for someone migrating from JUnit 3 or earlier versions.Notable differences
More details from comments:
@Beforeallows overriding parent class behavior, constructors force you to call parent class constructors@Rulemethods,@Beforeruns after all of those@Beforecause@Aftermethods to be called, Exceptions in constructor don’t