Here’re some basic JUnit annotations you should understand:java
1.@BeforeClass – Run once before any of the test methods in the class, public static void.net
2.@AfterClass – Run once after all the tests in the class have been run, public static voidcode
3.@Before – Run before @Test, public voidget
4.@After – Run after @Test,** public void**it
5.@Test – This is the test method to run,** public void**io
BasicAnnotationTest.javaclass
package com.mkyong; 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"); } }
輸出結果:test
@BeforeClass - runOnceBeforeClass @Before - runBeforeTestMethod @Test - test_method_1 @After - runAfterTestMethod @Before - runBeforeTestMethod @Test - test_method_2 @After - runAfterTestMethod @AfterClass - runOnceAfterClass