1. 程式人生 > >使用junit進行單元測試的註解的執行順序。

使用junit進行單元測試的註解的執行順序。

轉自:http://zhidao.baidu.com/link?url=chYfV-VFu4cK8t_sAMpYCglk-zl_JHlvx-9ink9sdD_LcrGnfBCrJJ2w2yOaDWyPGg9-ruGVdlt3Q8uLHxxLOt6u42uwBcdnsdzjMwbxBt_

http://blog.sina.com.cn/s/blog_666a2f670100pe75.html

Unit4中的Annotation(註解、註釋)
 
JUnit4 使用 Java 5 中的註解(annotation),以下是JUnit4 常用的幾個annotation介紹
@Before:初始化方法
@After:釋放資源
@Test:測試方法,在這裡可以測試期望異常和超時時間
@Ignore:忽略的測試方法
@BeforeClass:針對所有測試,只執行一次,且必須為static void
@AfterClass:針對所有測試,只執行一次,且必須為static void
一個JUnit4 的
單元測試
用例執行順序為: @BeforeClass –> @Before –> @Test –> @After –> @AfterClass 每一個測試方法的呼叫順序為: @Before –> @Test –> @After

大致程式碼如下:

package test;


import static org.junit.Assert.assertEquals;


import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;


/** 
* @author : suyuyuan
* @date :2016年6月16日 下午5:29:13 
* @version 1.0 
*/
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