單元測試是保證代碼質量的基石,能在早期發現邏輯錯誤,降低後期維護成本。本文通過一個完整的 Student 實體類測試案例,演示 JUnit 4 核心用法與最佳實踐。
package com.phicomme.hu;
public class Student {
private String name;
private String sex;
private int high;
private int age;
private String school;
public Student(String name, String sex, int high, int age, String school) {
this.name = name;
this.sex = sex;
this.high = high;
this.age = age;
this.school = school;
}
// Getter/Setter 省略...
/** 年齡設置帶業務驗證:>25 返回 false */
public boolean setAge(int age) {
if (age > 25) return false;
this.age = age;
return true;
}
}
package com.phicomme.test;
import com.phicomme.hu.Student;
import junit.framework.TestCase;
public class StudentTest01 extends TestCase {
private Student testStudent;
@Override
protected void setUp() throws Exception {
super.setUp();
testStudent = new Student("djm", "boy", 178, 24, "華東政法");
System.out.println("setUp()");
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
System.out.println("tearDown()");
}
public void testGetSex() {
assertEquals("boy", testStudent.getSex());
System.out.println("testGetSex()");
}
public void testGetAge() {
assertEquals(24, testStudent.getAge());
System.out.println("testGetAge()");
}
}
關鍵點:setUp() 在每個測試方法前執行,tearDown() 在每個測試方法後執行,保證測試隔離性。
package com.phicomme.test;
import com.phicomme.hu.Student;
import junit.framework.TestCase;
public class StudentTest extends TestCase {
private Student testStudent;
@Override
protected void setUp() throws Exception {
super.setUp();
testStudent = new Student("steven_hu", "boy", 170, 23, "上海理工");
}
public void testSetAge() {
assertTrue(testStudent.setAge(21)); // 合法年齡
}
public void testGetSchool() {
// 預期失敗:實際值 "上海理工" ≠ "南昌大學"
assertEquals("南昌大學", testStudent.getSchool());
}
public void testGetName() {
// 預期失敗:實際值 "steven_hu" ≠ "hdy"
assertEquals("hdy", testStudent.getName());
}
}
運行結果將顯示 Failure,這正是單元測試的價值——暴露代碼與預期不符。
package com.phicomme.test;
import junit.framework.Test;
import junit.framework.TestSuite;
public class AllTest {
public static Test suite() {
TestSuite suite = new TestSuite("All Tests for com.phicomme.test");
suite.addTestSuite(StudentTest.class);
suite.addTestSuite(StudentTest01.class);
return suite;
}
}
在 Eclipse 中右鍵 AllTest → Run As → JUnit Test 即可批量執行。
src/test/java)@Before/@After 註解(JUnit 4 風格)替代繼承 TestCase掌握單元測試基礎後,可進一步探索 Android 單元測試、UI 自動化測試等進階主題。