I'm new to unit test. About the purpose of using @Before
annotation in JUnit 4. I just don't know the point of using it:
public class FoodTestCase {
static private Food sandwich;
@BeforeClass
public static void initialise(){
sandwich = new Sandwich();
}
}
vs
public class FoodTestCase {
static private Food sandwich = new Sandwich();
}
What's the difference?
org.junit Annotating a public static void no-arg method with @BeforeClass causes it to be run once before any of the test methods in the class. The @BeforeClass methods of superclasses will be run before those of the current class, unless they are shadowed in the current class.
Before and BeforeClass in JUnit The function @Before annotation will be executed before each of test function in the class having @Test annotation but the function with @BeforeClass will be execute only one time before all the test functions in the class.
Key points in these differences are:@BeforeTest method executes only once before the first @Test method. @BeforeClass executes before each class.
JUnit's @BeforeClass annotation must be declared static if you want it to run once before all the @Test methods.
In this case it may not be necessary, as the initialization is really simple.
In case you have some logging, complex initialization or need to free some resources, you have to use @BeforeClass and @AfterClass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With