Testing
เขียนโค้ดเสร็จแล้ว อย่าเพิ่งดีใจครับ มันอาจจะทำงานได้ดีแค่ในเครื่องเราก็ได้ Rust ให้ความสำคัญกับการ Test มาก ถึงขนาดมี Test Runner ติดมากับ cargo เลย
ลองนึกภาพว่า Tests เป็นเหมือน “ตาข่ายนิรภัย” ที่จับ bugs ก่อนที่มันจะไปถึง production!
1. Unit Tests
Section titled “1. Unit Tests”1.1 Basic Structure
Section titled “1.1 Basic Structure”// Code ที่ต้องการ testpub fn add(a: i32, b: i32) -> i32 { a + b}
pub fn multiply(a: i32, b: i32) -> i32 { a * b}
// ============================================// Test module// #[cfg(test)] = compile เฉพาะเมื่อ test// ============================================#[cfg(test)]mod tests { // use super::* = import ทุกอย่างจาก parent module use super::*;
// #[test] = mark function เป็น test #[test] fn test_add() { assert_eq!(add(2, 3), 5); }
#[test] fn test_add_negative() { assert_eq!(add(-1, -1), -2); }
#[test] fn test_multiply() { assert_eq!(multiply(2, 3), 6); }}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google