Why in JUnit test 2 initializing and 2 final methods



  • Created JUnit test (first), found that there were two initial classes and two final methods:

    @BeforeClass
    public static void setUpClass() {
    }
    

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    1. What difference does @BeforeClass, @AfterClass from @Before, @After?
    2. What time does the initials start? before every call of the test methods, or when at the beginning?
    3. For what purpose and in what cases are @AfterClass and @After?



  • @BeforeClass is performed before the test, the initialisation of global variables, the reading of variable environment data, etc., is carried out one time at first.

    @Before to each method with annotations @Test. Used to create a folder where the @Test will be annotated test

    @After is performed after each method with annotations @Test. We can use the files and the folder that have been created above.

    @AfterClass shall be carried out after all methods with annotations @Test, i.e. at the end of the test, are used to collect logs, clean up data. ♪ ♪

        import org.junit.*;
    

    public class BasicAnnotationTest {

    // Run once, e.g. Database connection, connection pool
    @BeforeClass
    public static void runOnceBeforeClass() {
        System.out.println("@BeforeClass - runOnceBeforeClass");
    }
    
    // Run once, e.g close connection, cleanup
    @AfterClass
    public static void runOnceAfterClass() {
        System.out.println("@AfterClass - runOnceAfterClass");
    }
    
    // Should rename to @BeforeTestMethod
    // e.g. 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




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2