Testing Patterns
Patterns สำหรับ testing ใน Rust
Basic Test Structure
Section titled “Basic Test Structure”// Unit testfn add(a: i32, b: i32) -> i32 { a + b}
fn divide(a: i32, b: i32) -> Result<i32, String> { if b == 0 { Err("Division by zero".to_string()) } else { Ok(a / b) }}
#[cfg(test)]mod tests { use super::*;
#[test] fn test_add() { assert_eq!(add(2, 3), 5); }
#[test] fn test_add_negative() { assert_eq!(add(-1, 1), 0); }
#[test] fn test_divide_success() { assert_eq!(divide(10, 2), Ok(5)); }
#[test] fn test_divide_by_zero() { assert!(divide(10, 0).is_err()); }
#[test] #[should_panic] fn test_panic() { panic!("This test should panic"); }
#[test] #[should_panic(expected = "specific")] fn test_specific_panic() { panic!("specific error message"); }
#[test] #[ignore] fn expensive_test() { // Run with: cargo test -- --ignored std::thread::sleep(std::time::Duration::from_secs(10)); }}
fn main() { println!("add(2, 3) = {}", add(2, 3)); println!("divide(10, 2) = {:?}", divide(10, 2));}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google