0

I am learning to write unit tests in rust. However, I can't get my test running when they are not in src/lib.rs or src/main.rs.

I created a project with the following structure:

├── Cargo.lock
├── Cargo.toml
├── src
    ├── lib.rs
    └── main.rs
    └── functions.rs

and added the following code:

main.rs

#[cfg(test)]
mod test {
    #[test]
    fn test_main() {}
}

lib.rs

#[cfg(test)]
mod test {
    #[test]
    fn test_lib() {}
}

functions.rs

#[cfg(test)]
mod test {
    #[test]
    fn test_functions() { }
}

When I run cargo test, this is what I got:

Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running target\debug\deps\rust_unittests-b0ed92af162e0288.exe

running 1 test
test test::test_lib ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target\debug\deps\rust_unittests-c4edac234e8e3d9a.exe

running 1 test
test test::test_main ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests rust_unittests

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

The test function in main.rs and lib.rs were run as expected but the one in functions.rs wasn't.

I read the Rust book and several articles I Googled but none have mentioned this problem. What am I missing?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
san1127
  • 153
  • 2
  • 9
  • 1
    You need to have `mod functions;` in lib.rs (or main.rs, it's unclear from your code) in order to tell the compiler that the file needs to be read. – Shepmaster May 22 '19 at 15:03
  • You may wish to read the [Separating Modules into Different Files](https://doc.rust-lang.org/book/ch07-02-modules-and-use-to-control-scope-and-privacy.html#separating-modules-into-different-files) part of [*The Rust Programming Language*](https://doc.rust-lang.org/book/). – Shepmaster May 22 '19 at 15:05
  • Add an empty main in function.rs (`fn main() {}`). Then tell your Cargo manifest (here the `Cargo.toml` file) that there is a new executable crate (`[[bin]]`) whose `path` is `src/functions.rs`. `cargo test` will create an executable for excuting `src/functions.rs`'s tests. – air-dex May 25 '19 at 02:59

0 Answers0