@Before makes more sense to use in certain cases because it gets called AFTER the constructor for the class. This difference is important when you're using a mock framework like Mockito with @Mock annotations, because your @Before method will be called after the mocks are initialized. Then you can use your mocks to provide constructor arguments to the class under test.
I find this to be a very common pattern in my unit tests when using collaborating beans.
Here's an (admittedly contrived) example:
@RunWith(MockitoJUnitRunner.class)
public class CalculatorTest {
@Mock Adder adder;
@Mock Subtractor subtractor;
@Mock Divider divider;
@Mock Multiplier multiplier;
Calculator calculator;
@Before
public void setUp() {
calculator = new Calculator(adder,subtractor,divider,multiplier);
}
@Test
public void testAdd() {
BigDecimal value = calculator.add(2,2);
verify(adder).add(eq(2),eq(2));
}
}
@Before
, not@BeforeClass
? Check the difference here. – Pulsatile