Test注解的兩個屬性:expected和timeout
JUnit4:Test文檔中的解釋:
The Test
annotation supports two optional parameters.
The first, expected
, declares that a test method should throw an exception.
If it doesn't throw an exception or if it throws a different exception than the one declared, the test fails.
For example, the following test succeeds:
@Test(expected=IndexOutOfBoundsException.class) public void outOfBounds() { new ArrayList<Object>().get(1); }
The second optional parameter, timeout
, causes a test to fail if it takes longer than a specified amount of clock time (measured in milliseconds).
The following test fails:
@Test(timeout=100)
public void infinity() { while(true); }
文檔中說得比較清楚,下面再結合之前加減乘除的例子重復地解釋一下,以作鞏固。。
expected屬性
用來指示期望拋出的異常類型。
比如除以0的測試:
@Test(expected = Exception.class) public void testDivide() throws Exception { cal.divide(1, 0); }
拋出指定的異常類型,則測試通過 。
如果除數改為非0值,則不會拋出異常,測試失敗,報Failures。
timeout屬性
用來指示時間上限。
比如把這個屬性設置為100毫秒:
@Test(timeout = 100)
當測試方法的時間超過這個時間值時測試就會失敗。
(注意超時了報的是Errors,如果是值錯了是Failures)。
附上程序例子:
其中讓加法的時間延遲500毫秒。

package com.mengdd.junit4; public class Calculator { public int add(int a, int b) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } return a + b; } public int subtract(int a, int b) { return a - b; } public int multiply(int a, int b) { return a * b; } public int divide(int a, int b) throws Exception { if (0 == b) { throw new Exception("除數不能為0"); } return a / b; } }
測試類代碼:
加法方法測試加入了時間限制,導致超過時間時發生錯誤。
加入了除法除以零的拋出異常測試。

package com.mengdd.junit4; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.assertEquals;//靜態導入 public class CalculatorTest { private Calculator cal = null; @BeforeClass public static void globalInit() { System.out.println("global Init invoked!"); } @AfterClass public static void globalDestroy() { System.out.println("global Destroy invoked!"); } @Before public void init()// setUp() { cal = new Calculator(); System.out.println("init --> cal: " + cal); } @After public void destroy()// tearDown() { System.out.println("destroy"); } @Test(timeout = 100) public void testAdd() { System.out.println("testAdd"); int result = cal.add(3, 5); assertEquals(8, result); } @Test public void testSubtract() { System.out.println("testSubtract"); int result = cal.subtract(1, 6); assertEquals(-5, result); } @Test public void testMultiply() { System.out.println("testMultiply"); int result = cal.multiply(5, 9); assertEquals(45, result); } @Test(expected = Exception.class) public void testDivide() throws Exception { cal.divide(1, 0); } }
參考資料
聖思園張龍老師視頻教程。
JUnit4 chm格式文檔網盤下載鏈接:
JUnit 4.0:http://pan.baidu.com/share/link?shareid=539345&uk=2701745266