This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Test | |
public void testForRuntimeException() | |
{ | |
int a = 1 / 0; | |
} |
ดับเบิลคลิกที่เครื่องหมายกากาบาทสีแดง ที่หน้าต่างแสดงผลของการทดสอบ Eclipse ก็จะพาคุณไปหาโค๊ดบรรทัดที่แสดงปัญหา และตรง Failure Trace ก็จะบอกว่า java.lang.ArithmeticException : / by zero
เพราะว่ามันไม่มีความหมายในทางคณิตศาสตร์ พอไม่มีความหมาย เขาก็ไม่รู้จะสร้างซีพียูให้คำนวนการหารด้วยศูนย์ได้ยังไง จาวาจึงแสดง error ออกมากแทน แต่ถ้าเราต้องการทดสอบว่าฟังก์ชั่นนี้จะต้องได้ค่า error ออกมา ถ้าจะพูดให้ถูกกว่านี้ก็ควรว่า ได้ Exception ออกมา ในที่นี้คือ Arithmetic Exception.
วิธีเขียนเทสคือ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Test(expected = ArithmeticException.class) | |
public void testForRuntimeException() | |
{ | |
int a = 1 / 0; | |
} |
นอกจากนี้แล้ว คุณยังสามารถเขียนได้อีกว่า
@Test(expected = RuntimeException.class)
@Test(expected = Exception.class)
ที่เป็นแบบนี้ได้ก็เพราะว่า
ArithmeticException เป็นลูกของ RuntimeException
RuntimeException เป็นลูกของ Exception อีกที
ซึ่งก็ทำให้ ArithmeticException เป็นหลานของ Exception อย่างถูกกฏหมายตรงตามสำเนาทะเบียนบ้าน
สำหรับเรื่อง Interface กับเรื่อง Inheritance เราจะไม่พูดในที่นี้นะครับ ใครสงสัยตรงไหนก็สอบถามได้ตามคอมเมนต์ครับ
มาถึงเรื่องของเวลา สมมุติเราต้องการทดสอบว่าฟังก็ชั่นหนึ่งๆ สามารถทำงานให้เสร็จได้ตามเวลาที่กำหนดเป็นมิลิวินาทีได้หรือไม่ ( มิลิวินาที ก็คือ 1 / 1,000 ของวินาที ) ก็ทำได้ง่ายๆดังโค๊ดข้างล่าง
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static org.junit.Assert.assertTrue; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.List; | |
//-------------------------------------- | |
@Test(timeout = 400) | |
public void testSortTimeOut() | |
{ | |
java.util.List<Double> nums = new java.util.ArrayList<Double>(); | |
for(int i = 0 ; i < 99999 ;i++) | |
{ | |
nums.add(Math.random()); | |
} | |
Collections.sort(nums); | |
boolean asc = true; | |
for(int i = 0 ; i < nums.size() -1 ; i++) | |
{ | |
if(nums.get(i) > nums.get(i+1)) | |
{ | |
asc = false; | |
break; | |
} | |
} | |
assertTrue(asc); | |
} |
จากข้างบนคุณจะเห็น พารามิเตอร์ของ
@Test
เป็น timeout = 400
หมายความว่าหากฟังก์ชั่นนี้ใช้เวลาเกินกว่า 400 มิลิวินาที ก็จะไม่ผ่านเทส คุณสามารถลองเปลี่ยนเป็น 100 หรือ 50 แล้วแต่สเปกเครื่องที่คุณใช้ครับ