JUnit4 中@AfterClass @BeforeClass @after @before的区别对比

JUnit4使用Java5中的注解(annotation),以下是JUnit4常用的几个annotation: 
@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; 

[java] 
 
  1. public class JUnit4Test {     
  2.     @Before    
  3.     public void before() {     
  4.         System.out.println("@Before");     
  5.     }     
  6.       
  7.     @Test    
  8.          /**   
  9.           *Mark your test cases with @Test annotations.    
  10.           *You don’t need to prefix your test cases with “test”.   
  11.           *tested class does not need to extend from “TestCase” class.   
  12.           */    
  13.     public void test() {     
  14.         System.out.println("@Test");     
  15.         assertEquals(5 + 5, 10);     
  16.     }     
  17.       
  18.     @Ignore    
  19.     @Test    
  20.     public void testIgnore() {     
  21.         System.out.println("@Ignore");     
  22.     }     
  23.       
  24.     @Test(timeout = 50)     
  25.     public void testTimeout() {     
  26.         System.out.println("@Test(timeout = 50)");     
  27.         assertEquals(5 + 5, 10);     
  28.     }     
  29.       
  30.     @Test(expected = ArithmeticException.class)     
  31.     public void testExpected() {     
  32.         System.out.println("@Test(expected = Exception.class)");     
  33.         throw new ArithmeticException();     
  34.     }     
  35.       
  36.     @After    
  37.     public void after() {     
  38.         System.out.println("@After");     
  39.     }     
  40.       
  41.     @BeforeClass    
  42.     public static void beforeClass() {     
  43.         System.out.println("@BeforeClass");     
  44.     };     
  45.       
  46.     @AfterClass    
  47.     public static void afterClass() {     
  48.         System.out.println("@AfterClass");     
  49.     };     
  50. };    


输出结果: 
@BeforeClass 
@Before 
@Test(timeout = 50) 
@After 
@Before 
@Test(expected = Exception.class) 
@After 
@Before 
@Test 
@After 
@AfterClass 

不经历风雨,哪来彩虹?
原文地址:https://www.cnblogs.com/yuyu666/p/10149656.html