Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I run #[test]s defined in main()?

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?

like image 404
RVilchez Avatar asked Oct 15 '25 18:10

RVilchez


1 Answers

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.

like image 146
Finomnis Avatar answered Oct 17 '25 10:10

Finomnis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!