Created a JUnit test (for the first time), found that 2 initializing classes and two final methods were created:

@BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } 
  1. What is the difference between @BeforeClass, @AfterClass and @Before, @After?
  2. At what point do the initializers run? Before each call of testing methods, or once at the beginning?
  3. What and in what cases need @AfterClass and @After?
  • 2
    Well, if the name does not hint to you, then try to write output to the console to each method, and everything will become clear. :) The first is performed once , the second before or after each test . - enzo

1 answer 1

@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