@Before:初始化方法 對於每一個測試方法都要執行一次(注意與BeforeClass區別,後者是對於所有方法執行一次)
@After:釋放資源 對於每一個測試方法都要執行一次(注意與AfterClass區別,後者是對於所有方法執行一次)
@Test:測試方法,在這裏可以測試期望異常和超時時間
@Test(expected=ArithmeticException.class)檢查被測方法是否拋出ArithmeticException異常
@Ignore:忽略的測試方法
@BeforeClass:針對所有測試,只執行一次,且必須爲static void
@AfterClass:針對所有測試,只執行一次,且必須爲static void
一個JUnit4的單元測試用例執行順序爲:
@BeforeClass -> @Before -> @Test -> @After -> @AfterClass;
每一個測試方法的調用順序爲:
@Before -> @Test -> @After;
public class JUnit4Test {
@Before
public void before() {
System.out.println("@Before");
}
@Test
/**
*Mark your test cases with @Test annotations.
*You don’t need to prefix your test cases with “test”.
*tested class does not need to extend from “TestCase” class.
*/
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
@BeforeClass and @AfterClass | @Before and @After |
在一個類中只可以出現一次 |
在一個類中可以出現多次,即可以在多個方法的聲明前加上這兩個Annotaion標籤,執行順序不確定 |
方法名不做限制 | 方法名不做限制 |
在類中只運行一次 | 在每個測試方法之前或者之後都會運行一次 |
@BeforeClass父類中標識了該Annotation的方法將會先於當前類中標識了該Annotation的方法執行。 |
@Before父類中標識了該Annotation的方法將會先於當前類中標識了該Annotation的方法執行。 @After父類中標識了該Annotation的方法將會在當前類中標識了該Annotation的方法之後執行 |
必須聲明爲public static | 必須聲明爲public 並且非static |
所有標識爲@AfterClass的方法都一定會被執行,即使在標識爲@BeforeClass的方法拋出異常的的情況下也一樣會。 | 所有標識爲@After 的方法都一定會被執行,即使在標識爲 @Before 或者 @Test 的方法拋出異常的的情況下也一樣會。 |
@BeforeClass 和 @AfterClass 對於那些比較“昂貴”的資源的分配或者釋放來說是很有效的,因爲他們只會在類中被執行一次。相比之下對於那些需要在每次運行之前都要初始化或者在運行之後 都需要被清理的資源來說使用@Before和@After同樣是一個比較明智的選擇。