I'm learning Rust and I want to test a simple function inside 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");
}
When I run cargo test
no test are found and this warning shows up:
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
But, if I define both the adder function and the test function outside the main function, it works:
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
Why didn't my first try work?
CodePudding user response:
Nested tests are not possible.
There was a request to add that, but the outcome was that this is impossible to implement:
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.
The best solution, in my opinion, would be to restructure your code so that the method you want to test isn't nested anymore.