- Difference between each annotation in
JUnit 4 & 5
+-------------------------------------------------------------------------------------------------------+
¦ Feature ¦ Junit 4 ¦ Junit 5 ¦
¦--------------------------------------------------------------------------+--------------+-------------¦
¦ Execute before all test methods of the class are executed. ¦ @BeforeClass ¦ @BeforeAll ¦
¦ Used with static method. ¦ ¦ ¦
¦ For example, This method could contain some initialization code ¦ ¦ ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute after all test methods in the current class. ¦ @AfterClass ¦ @AfterAll ¦
¦ Used with static method. ¦ ¦ ¦
¦ For example, This method could contain some cleanup code. ¦ ¦ ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute before each test method. ¦ @Before ¦ @BeforeEach ¦
¦ Used with non-static method. ¦ ¦ ¦
¦ For example, to reinitialize some class attributes used by the methods. ¦ ¦ ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute after each test method. ¦ @After ¦ @AfterEach ¦
¦ Used with non-static method. ¦ ¦ ¦
¦ For example, to roll back database modifications. ¦ ¦ ¦
+-------------------------------------------------------------------------------------------------------+
-
Reference: Difference between
@Before
,@BeforeClass
,@BeforeEach
and@BeforeAll
-
Order of Execution: Dashed box -> optional annotation
- Example:
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
- Reference: install-maven-mac-os
- Reference: playwright-java-tutorial