How do I write a Rust unit test that ensures that a panic has occurred?
我有一个在某些情况下
我可以产生一个新任务,并检查该任务是否紧急。是否有意义?
在我的情况下不适合返回
我希望将对
1 | let m = m1 + m2 + m3; |
其中
1 | let m = ((m1 + m2).unwrap() + m3).unwrap() |
同时,
您可以在Rust书的"测试"部分中找到答案。更具体地说,您需要
1 2 3 4 5 6 7 | #[test] #[should_panic] fn test_invalid_matrices_multiplication() { let m1 = Matrix::new(3, 4); // assume these are dimensions let m2 = Matrix::new(5, 6); m1 * m2 } |
像弗朗西斯·加恩一样??在他的回答中提到,我还发现
从Rust 1.9.0开始,
1 2 3 4 5 6 | #[test] fn test_something() { ... //<-- Any panics here will cause test failure (good) let result = std::panic::catch_unwind(|| <expected_to_panic_operation_here>); assert!(result.is_err()); //probe further for specific error type here, if desired } |
请注意,它无法捕捉到令人放松的panic(例如
如果要断言仅测试功能的特定部分失败,请使用
Rust标准库本身中的多个测试都使用此技术。
使用以下
1 2 3 4 5 6 7 8 9 | use std::panic; fn catch_unwind_silent<F: FnOnce() -> R + panic::UnwindSafe, R>(f: F) -> std::thread::Result<R> { let prev_hook = panic::take_hook(); panic::set_hook(Box::new(|_| {})); let result = panic::catch_unwind(f); panic::set_hook(prev_hook); result } |
作为附录:@ U007D提出的解决方案也可以在doctests中使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | /// My identity function that panic for an input of 42. /// /// ``` /// assert_eq!(my_crate::my_func(23), 23); /// /// let result = std::panic::catch_unwind(|| my_crate::my_func(42)); /// assert!(result.is_err()); /// ``` pub fn my_func(input: u32) -> u32 { if input == 42 { panic!("Error message."); } else { input } } |