注釋 @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