JUnit4通过注解的方式来识别测试方法。目前支持的主要注解有:

  • @BeforeClass 全局只会执行一次,而且是第一个运行
  • @Before 在测试方法运行之前运行
  • @Test 测试方法
  • @After 在测试方法运行之后允许
  • @AfterClass 全局只会执行一次,而且是最后一个运行
  • @Ignore 忽略此方法

下面举一个样例:

  • import org.junit.After;  
  • import org.junit.AfterClass;  
  • import org.junit.Assert;  
  • import org.junit.Before;  
  • import org.junit.BeforeClass;  
  • import org.junit.Ignore;  
  • import org.junit.Test;  
  •    
  • public class Junit4TestCase {  
  •    
  •     @BeforeClass  
  •     public static void setUpBeforeClass() {  
  •         System.out.println("Set up before class");  
  •     }  
  •    
  •     @Before  
  •     public void setUp() throws Exception {  
  •         System.out.println("Set up");  
  •     }  
  •    
  •     @Test  
  •     public void testMathPow() {  
  •         System.out.println("Test Math.pow");  
  •         Assert.assertEquals(4.0, Math.pow(2.0, 2.0), 0.0);  
  •     }  
  •    
  •     @Test  
  •     public void testMathMin() {  
  •         System.out.println("Test Math.min");  
  •         Assert.assertEquals(2.0, Math.min(2.0, 4.0), 0.0);  
  •     }  
  •    
  •         // 期望此方法抛出NullPointerException异常  
  •     @Test(expected = NullPointerException.class)  
  •     public void testException() {  
  •         System.out.println("Test exception");  
  •         Object obj = null;  
  •         obj.toString();  
  •     }  
  •    
  •         // 忽略此测试方法  
  •     @Ignore  
  •     @Test  
  •     public void testMathMax() {  
  •           Assert.fail("没有实现");  
  •     }  
  •         // 使用“假设”来忽略测试方法  
  •     @Test  
  •     public void testAssume(){  
  •         System.out.println("Test assume");  
  •                 // 当假设失败时,则会停止运行,但这并不会意味测试方法失败。  
  •         Assume.assumeTrue(false);  
  •         Assert.fail("没有实现");  
  •     }  
  •    
  •     @After  
  •     public void tearDown() throws Exception {  
  •         System.out.println("Tear down");  
  •     }  
  •    
  •     @AfterClass  
  •     public static void tearDownAfterClass() {  
  •         System.out.println("Tear down After class");  
  •     }  
  •    
  • }  
  •  

     

    Junit3的package是junit.framework,而Junit4是org.junit
    执行此用例后,控制台会输出

    写道
    Set up before class
    Set up
    Test Math.pow
    Tear down
    Set up
    Test Math.min
    Tear down
    Set up
    Test exception
    Tear down
    Set up
    Test assume
    Tear down
    Tear down After class

     

     

    可以看到,执行次序是@BeforeClass -> @Before -> @Test -> @After -> @Before -> @Test -> @After -> @AfterClass@Ignore会被忽略。

    相关文章:

    • 2021-09-23
    • 2022-12-23
    • 2021-12-28
    • 2022-12-23
    • 2021-10-14
    • 2021-12-31
    猜你喜欢
    • 2021-06-23
    • 2021-11-20
    • 2022-12-23
    • 2022-12-23
    • 2021-08-24
    • 2021-09-13
    • 2021-11-28
    相关资源
    相似解决方案