我正在学习 Rust,我想测试 main.rs 中的一个简单函数:
fn main() {
fn adder(n: u64, m:u64) -> u64 {
assert!(n != 0 && m !=0);
n + m
}
#[test]
fn test_gcd(){
assert_eq!(adder(1, 10), 11);
assert_eq!(adder(100, 33), 133);
}
println!("{}", adder(3, 4));
println!("The END");
}
当我运行 cargo test
时,没有找到任何测试,并显示此警告:
warning: cannot test inner items
--> src\main.rs:7:5
|
7 | #[test]
| ^^^^^^^
|
= note: `#[warn(unnameable_test_items)]` on by default
= note: this warning originates in the attribute macro `test` (in Nightly builds, run with -Z macro-backtrace for more info)
warning: `rust_prueba` (bin "rust_prueba" test) generated 1 warning
Finished test [unoptimized + debuginfo] target(s) in 0.58s
Running unittests src\main.rs (target\debug\deps\rust_prueba-e1ba8a7bcfb64cfc.exe)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
但是,如果我在主函数的外部同时定义加法器函数和测试函数,它就可以工作:
fn main() {
println!("{}", adder(3, 4));
println!("The END");
}
fn adder(n: u64, m:u64) -> u64 {
assert!(n != 0 && m !=0);
n + m
}
#[test]
fn test_gcd(){
assert_eq!(adder(1, 10), 11);
assert_eq!(adder(100, 33), 133);
}
cargo 测试
:
running 1 test
test test_gcd ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
为什么我的第一次尝试没有成功?
最佳答案
嵌套测试是不可能的。
有一个request to add that , 但结果是这是不可能实现的:
The problem with this is that the test harness needs to access the inner functions, which it can't do because you can't name them.
在我看来,最好的解决方案是重构您的代码,以便您要测试的方法不再嵌套。
关于unit-testing - 为什么我不能运行 main() 中定义的#[test]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73177482/