如何编写Rust单元测试以确保发生panic?

How do I write a Rust unit test that ensures that a panic has occurred?

我有一个在某些情况下panic s的Rust函数,我希望编写一个测试用例来验证该函数是否惊慌。除了assert!assert_eq!宏之外,我什么都找不到。有测试这种情况的机制吗?

我可以产生一个新任务,并检查该任务是否紧急。是否有意义?

在我的情况下不适合返回Result<T, E>

我希望将对Add特征的支持添加到我正在实现的Matrix类型中。这种加法的理想语法如下:

1
let m = m1 + m2 + m3;

其中m1m2m3都是矩阵。因此,结果类型Add应该为Matrix。类似于以下内容的内容太含糊了:

1
let m = ((m1 + m2).unwrap() + m3).unwrap()

同时,add()函数需要验证所添加的两个矩阵的维数相同。因此,如果尺寸不匹配,add()需要惊慌。可用的选项是panic!()


您可以在Rust书的"测试"部分中找到答案。更具体地说,您需要#[should_panic]属性:

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
}


像弗朗西斯·加恩一样??在他的回答中提到,我还发现#[should_panic]属性的粒度不足以用于更复杂的测试-例如,如果我的测试设置由于某种原因而失败(即我编写了一个错误的测试),我会希望将紧急情况视为失败!

从Rust 1.9.0开始,std::panic::catch_unwind()可用。它允许您将您希望惊慌的代码放入一个闭包中,并且只有该代码发出的panic才被认为是期望的(即通过测试)。

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(例如std::process::abort())。


如果要断言仅测试功能的特定部分失败,请使用std::panic::catch_unwind()并检查其是否返回Err,例如使用is_err()。在复杂的测试功能中,这有助于确保测试不会因早期失败而错误通过。

Rust标准库本身中的多个测试都使用此技术。


使用以下catch_unwind_silent而不是常规的catch_unwind来实现预期异常的输出静音:

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
    }
}