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.
Similarly function with @After
annotation will be executed after each of test function in the class having @Test
annotation but the function with @AfterClass
will be execute only one time after all the test functions in the class.
SampleClass
public class SampleClass {
public String initializeData(){
return "Initialize";
}
public String processDate(){
return "Process";
}
}
SampleTest
public class SampleTest {
private SampleClass sampleClass;
@BeforeClass
public static void beforeClassFunction(){
System.out.println("Before Class");
}
@Before
public void beforeFunction(){
sampleClass=new SampleClass();
System.out.println("Before Function");
}
@After
public void afterFunction(){
System.out.println("After Function");
}
@AfterClass
public static void afterClassFunction(){
System.out.println("After Class");
}
@Test
public void initializeTest(){
Assert.assertEquals("Initailization check", "Initialize", sampleClass.initializeData() );
}
@Test
public void processTest(){
Assert.assertEquals("Process check", "Process", sampleClass.processDate() );
}
}
Output
Before Class
Before Function
After Function
Before Function
After Function
After Class
In Junit 5
@Before = @BeforeEach
@BeforeClass = @BeforeAll
@After = @AfterEach
@AfterClass = @AfterAll
@BeforeClas
is static. It runs before test class instances are created. – Alkyd