標籤:.com 學習 except hid test 逾時 png public 單位
accuracy test(結果準確性測試)
例如,Assert.assertEquals(expected, actual)。
如果結果不符合期望則產生failure。說明程式邏輯有問題。
failure test(拋出異常測試)
expected屬性用來指示期望拋出的異常類型。例如,@Test(expected = IllegalArgumentException.class)。
如果結果不符合期望則產生failure。說明程式邏輯有問題。
stress test(已耗用時間測試)
timeout屬性用來指示時間上限,單位是毫秒。例如,@Test(timeout = 300)。
如果逾時則產生error。說明程式本身效能達不到要求。
舉個例子
1 package edu.zju.cst.Student; 2 3 public class Student { 4 private String name; 5 6 public String getName() { 7 return name; 8 } 9 10 public void setName(String name) {11 this.name = name;12 }13 14 public String speak(String stm) {15 try {16 Thread.sleep(400);17 } catch (InterruptedException e) {18 e.printStackTrace();19 }20 21 return name + ": " + stm;22 }23 }
Student.java
1 package edu.zju.cst; 2 3 import org.junit.After; 4 import org.junit.Before; 5 import org.junit.Test; 6 7 import edu.zju.cst.Student.Student; 8 import junit.framework.Assert; 9 10 public class StudentAccuracyTest {11 private Student student;12 13 @Before14 public void setUp() {15 student = new Student();16 student.setName("Tom");17 }18 19 @Test20 public void testSpeak() {21 String expected = "Tom: hello";22 String actual = student.speak("hell");23 Assert.assertEquals(expected, actual);24 }25 26 @After27 public void tearDown() {28 29 }30 }
StudentAccuracyTest.java
1 package edu.zju.cst; 2 3 import org.junit.After; 4 import org.junit.Before; 5 import org.junit.Test; 6 7 import edu.zju.cst.Student.Student; 8 9 public class StudentFailureTest {10 private Student student;11 12 @Before13 public void setUp() {14 student = new Student();15 student.setName("Tom");16 }17 18 @Test(expected = IllegalArgumentException.class)19 public void testSpeak() throws IllegalArgumentException {20 student.speak("hell");21 }22 23 @After24 public void tearDown() {25 26 }27 }
StudentFailureTest.java
1 package edu.zju.cst; 2 3 import org.junit.After; 4 import org.junit.Before; 5 import org.junit.Test; 6 7 import edu.zju.cst.Student.Student; 8 9 public class StudentStressTest {10 private Student student;11 12 @Before13 public void setUp() {14 student = new Student();15 student.setName("Tom");16 }17 18 @Test(timeout = 300)19 public void testSpeak() {20 student.speak("hell");21 }22 23 @After24 public void tearDown() {25 26 }27 }
StudentStressTest.java
1 package edu.zju.cst; 2 3 import org.junit.runner.RunWith; 4 import org.junit.runners.Suite; 5 import org.junit.runners.Suite.SuiteClasses; 6 7 @RunWith(Suite.class) 8 @SuiteClasses({StudentAccuracyTest.class, StudentFailureTest.class, 9 StudentStressTest.class})10 public class TestSuite {11 12 }
TestSuite.java
參考資料
JUnit單元測試的幾個規律總結
JUnit4:Test註解的兩個屬性:expected和timeout
Java課程學習筆記 — JUnit accuracy/failure/stress test區別