首页 > 技术文章 > 注释 @before @After

WLCYSYS 2020-05-08 13:37 原文

 

  注释  @before @After

 

package cn.nynu.test;

 
import static org.junit.Assert.*;
 
import org.junit.*;

//@HepengWu
public class TestMethodTestExample {
 
    // @BeforeClass  只有一个
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        System.out.println("This is a BeforeClass.");
    }
 
    //@AfterClass 只有一个
    @AfterClass  
    public static void tearDownAfterClass() throws Exception {
        System.out.println("This is an AfterClass.");
    }
 
    //@Before 可以有多个
    @Before
    public void beforeZero() {
        System.out.println("This is a Before  Zero.");
    }
    
    @Before
    public void beforeOne() {
        System.out.println("This is a Before  One. ");
    }
 
    //@After 可以有多个
    
    @After
    public void afterZero() {
        System.out.println("This is a After  Zero. ");
    }
    @After
    public void afterOne() {
        System.out.println("This is a After  One.");
    }
    
    
    /*
     * @Test 运行顺序:
      *   测试类实例化->运行@BeforeClass->运行@Before->运行@Test->运行@After->运行@AfterClass .
      *   注意:这里有分别都有两个@ Before @After
     */

    @Test(timeout = 10000)
    public void testadd() {
        TestDemo a = new TestDemo();
        assertEquals(6, a.add(3, 3));
        System.out.println("This is a AddTest.");
    }
    
    /*
     * @Test 运行顺序:
      *   测试类实例化->运行@BeforeClass->运行@Before->运行@Test->运行@After->运行@AfterClass .
     */
 
    @Test
    public void testdivision() {
        TestDemo a = new TestDemo();
        
        assertEquals(3, a.division(6, 2));
        System.out.println("This is a DivisionTest.");
    }
    
    
    
    
    //由于注释的@Ignore; 所以下面的测试不再进行
    /*
     * @Test 运行顺序:
      *   测试类实例化->运行@BeforeClass->运行@Before->(不运行@Test)——->运行@After->运行@AfterClass .
     */
    @Ignore
    @Test
    public void test_ignore() {
        TestDemo a = new TestDemo();
        assertEquals(6, a.add(1, 5));
        System.out.println("This is a test_ignore.");
    }

    /*
     * fail() 错误的 蓝色×代 表failure,红色×代表error。error如除数 为0
     */
    /*
     * @Test public void testFail() { try {
     * fail("should hava thrown an exception "); } catch(RuntimeException e) {
     * assertTrue(true);
     * 
     * } }
     */
}
      
 
class TestDemo extends Thread {
 
    int result;
 
    public int add(int a, int b) {
        try {
            sleep(1000);
            result = a + b;
        } catch (InterruptedException e) {
        }
        return result;
    }
 
    public int division(int a, int b) {
        return result = a / b;
    }
}

  测试结果:

 

 

 

 

 

 

 

     参考:https://blog.csdn.net/wangpeng047/article/details/9628449

推荐阅读