我如何编写一个 Rust 单元测试来确保发生了恐慌? [英] How do I write a Rust unit test that ensures that a panic has occurred?

查看:28
本文介绍了我如何编写一个 Rust 单元测试来确保发生了恐慌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在某些条件下 panic 的 Rust 函数,我希望编写一个测试用例来验证该函数是否处于恐慌状态.除了 assert!assert_eq! 宏之外,我找不到任何东西.是否有一些机制可以测试这个?

I have a Rust function that panics under some condition and I wish to write a test case to validate whether the function is panicking or not. I couldn't find anything except the assert! and assert_eq! macros. Is there some mechanism for testing this?

我可以生成一个新任务并检查该任务是否发生恐慌.是否有意义?

I could spawn a new task and checking whether that task panics or not. Does it make sense?

返回 Result 不适合我的情况.

Returning a Result<T, E> is not suitable in my case.

我希望为我正在实现的 Matrix 类型添加对 Add 特征的支持.这种添加的理想语法如下所示:

I wish to add support for the Add trait to a Matrix type I am implementing. The ideal syntax for such addition would look like:

let m = m1 + m2 + m3;

其中 m1m2m3 都是矩阵.因此,add 的结果类型应该是 Matrix.像下面这样的东西太神秘了:

where m1, m2, m3 are all matrices. Hence, the result type of add should be Matrix. Something like the following would be too cryptic:

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

同时,add() 函数需要验证被添加的两个矩阵是否具有相同的维度.因此,如果维度不匹配,add() 需要恐慌.可用选项是 panic!().

At the same time, the add() function needs to validate that the two matrices being added have same dimension. Thus, add() needs to panic if the dimensions don't match. The available option is panic!().

推荐答案

您可以在 测试 部分.更具体地说,您需要 #[should_panic] 属性:

You can find the answer in testing section of the Rust book. More specifically, you want #[should_panic] attribute:

#[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 单元测试来确保发生了恐慌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆