我正在学习Rust,我想在main中测试一个简单的函数.rs as:
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
但是,如果我同时定义加法器函数和测试函数outside作为主函数,它可以工作:
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 test
:
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
为什么我的第一次try 没有成功?