JUnit Annotation——JUnit单元测试中眉批@详解[转]
JUnit Annotation——JUnit单元测试中批注@详解[转]
几种常用的测试批注:
@Test:进行测试的方法
@Before:初始化方法,每个@Test批注的方法执行前都会先调用此方法
@After:释放资源,每个@Test批注的方法执行后都会调用此方法
@BeforeClass:必须为static void,测试类中第一个执行的方法,只执行一次
@AfterClass:必须为static void,测试类中最后一个执行的方法,只执行一次
@Ignore:忽略的测试方法,不影响最终测试结果是通过还是没通过
一个JUnit 4 的单元测试用例执行顺序为:
@BeforeClass –> @Before –> @Test –> @After –> @AfterClass
每一个测试方法的调用顺序为:
@Before –> @Test –> @After
这里并不是所有部分都得有,@Test是核心,其他的都没定义也可以。
下面有个例子说明下:
import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; public class JUnit4Test { @Before public void before() { System.out.println("@Before"); } @Test public void test() { System.out.println("@Test"); assertEquals(5 + 5, 10); } @Ignore @Test public void testIgnore() { System.out.println("@Ignore"); } @Test(timeout = 50) public void testTimeout() { System.out.println("@Test(timeout = 50)"); assertEquals(5 + 5, 10); } @Test(expected = ArithmeticException.class) public void testExpected() { System.out.println("@Test(expected = Exception.class)"); throw new ArithmeticException(); } @After public void after() { System.out.println("@After"); } @BeforeClass public static void beforeClass() { System.out.println("@BeforeClass"); }; @AfterClass public static void afterClass() { System.out.println("@AfterClass"); }; };
输出结果
@BeforeClass
@Before
@Test(timeout = 50)
@After
@Before
@Test(expected = Exception.class)
@After
@Before
@Test
@After
@AfterClass