@BeforeClass runs before the test. here they perform initialization of global variables, reading data from the environment variable of the environment, etc. performed 1 time at the beginning
@Before is executed before each method with the annotation @Test. You can use to create a folder where the test with the annotation @Test will create a file
@After executed after each method with the annotation @Test. You can use to delete the files and folder you created above. can be used as a log separator
@AfterClass is executed after calls to all methods with the @Test annotation, that is, at the end of the test. used to collect logs, data stripping ...
import org.junit.*; public class BasicAnnotationTest { // Run once, eg Database connection, connection pool @BeforeClass public static void runOnceBeforeClass() { System.out.println("@BeforeClass - runOnceBeforeClass"); } // Run once, eg close connection, cleanup @AfterClass public static void runOnceAfterClass() { System.out.println("@AfterClass - runOnceAfterClass"); } // Should rename to @BeforeTestMethod // eg Creating an similar object and share for all @Test @Before public void runBeforeTestMethod() { System.out.println("@Before - runBeforeTestMethod"); } // Should rename to @AfterTestMethod @After public void runAfterTestMethod() { System.out.println("@After - runAfterTestMethod"); } @Test public void test_method_1() { System.out.println("@Test - test_method_1"); } @Test public void test_method_2() { System.out.println("@Test - test_method_2"); } }
Output
@BeforeClass - runOnceBeforeClass @Before - runBeforeTestMethod @Test - test_method_1 @After - runAfterTestMethod @Before - runBeforeTestMethod @Test - test_method_2 @After - runAfterTestMethod @AfterClass - runOnceAfterClass