[英]Run "should_panic" tests with different inputs
假设以下 function 从u8
获取第 n 位:
fn get_bit(&self, n: u8) -> bool {
if n > 7 {
panic!("Overflow detected while using `get_bit`: Tried to get the {n}th bit.");
}
let result = *self >> n & 1;
if result == 1 {
return true;
} else {
return false;
}
}
基本(紧急情况)测试如下所示:
#[test]
#[should_panic]
fn get_bit_panic_ut() {
0b0000_0000.get_bit(8);
}
如您所见,这仅测试 8 作为输入。 我想确保这个 function 会对 8 到 255 之间的任何输入产生恐慌。所以我天真的尝试是:
#[test]
#[should_panic]
fn get_bit_panic_ut() {
for i in 8..=255 {
println!("{i}"); // For demonstration purposes
0b0000_0000.get_bit(i);
}
}
如果我使用--nocapture
标志运行上面的代码,我可以看到测试执行在 8 之后停止。所以我的问题是如何测试这里的所有其他情况?
我遇到的一个可能有效的选项是rtest crate 。 我想知道 rust 是否为这种情况提供任何开箱即用的机制。
不 - 但你可以很容易地模拟它:
#[test]
fn get_bit_panic_ut() {
for i in 8..=255 {
println!("{i}"); // For demonstration purposes
assert!(std::panic::catch_unwind(|| 0b0000_0000.get_bit(i)).is_err());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.