การทดสอบใน Java เบื้องต้น
Maria Milusheva
Senior Software Engineer
แนวคิดหลัก 2 ประการ:
Unit - ส่วนที่เล็กที่สุดของแอปพลิเคชันที่ทดสอบได้ เช่น เมธอด
Unit testing - การทดสอบที่มุ่งตรวจสอบความถูกต้องของ "unit" เดียวของโค้ด โดยแยกออกจากส่วนอื่นของแอปพลิเคชัน
หมายเหตุ:
Unit testing เน้นที่ตรรกะขนาดเล็ก ไม่ใช่ภาพรวมทั้งหมด
การทดสอบประเภทอื่นเน้นภาพรวม (เช่น integration)
JUnit ได้ชื่อนี้เพราะกรณีใช้งานหลักคือ unit testing



assertTrue() ตรวจสอบว่าเงื่อนไขเป็นจริง: List<String> list = new ArrayList<>();
assertTrue(list.isEmpty()); // No error
assertFalse() ตรวจสอบตรงกันข้าม:List<String> list = new ArrayList<>();
list.add("A");
assertFalse(list.isEmpty()); // No error
ตัวแปรที่เป็น null อาจทำให้เกิด NullPointerException!
ใช้ assertNull() และ assertNotNull() เพื่อตรวจสอบว่าตัวแปรเป็นหรือไม่เป็น null
กรณีใช้งานทั่วไป: ตรวจสอบว่าค่าที่ดึงมาจากที่ใดที่หนึ่งไม่เป็น null
Map<String, Integer> catalogue = new HashMap<>();
catalogue.put("item1", 10);
// No errors
assertNotNull(catalogue.get("item1"));
assertNull(catalogue.get("item2"));
สมมติว่าต้องการตรวจสอบว่ามีการโยน ArrayIndexOutOfBoundsException:
public String getIndex(String[] array, int index) {
return array[index];
}
JUnit มีหลายวิธีในการทำเช่นนี้!
JUnit มี assertThrows() แต่ใช้ไวยากรณ์ Java ขั้นสูง (lambda expression)
สามารถใช้ assertInstanceOf() แบบนี้ได้:
try {
getIndex(new String[]{}, 4);
} catch (Exception e) {
// Pass the expected class of the exception and the exception itself
assertInstanceOf(ArrayIndexOutOfBoundsException.class, e);
}
โปรเจกต์ทั่วไปมี unit test หลายร้อยตัว
ควรเบาและเข้าใจง่าย
ควรมีชื่อที่สื่อความหมาย เพื่อให้รู้ทันทีว่าผิดพลาดที่จุดใดเมื่อ test ล้มเหลว
ตัวอย่างเช่น: methodUnderTest_expectedBehavior_conditions()
การทดสอบใน Java เบื้องต้น