how import the mod source file to test file in Rust

54 Views Asked by At

the structure of project like this:

.
├── Cargo.lock
├── Cargo.toml
├── demo.txt
├── src
│   ├── lib.rs
│   ├── lifetime_demo
│   │   └── mod.rs
│   ├── main.rs
└── tests
    └── trait_test.rs

the mod.rs of lifetime_demo path:

    pub mod lifetime_mod {
        pub fn show() {}
    }

the test.rs code

    use demo::lifetime_demo::lifetime_mod;
    #[test]
    fn test_trait() {
        lifetime_mod::show();
    }

when run 'cargo test' in /tests path, it tips error:

error[E0432]: unresolved import `demo::lifetime_demo`
 --> tests/trait_test.rs:3:11
  |
3 | use demo::lifetime_demo::lifetime_mod;
  |           ^^^^^^^^^^^^^ could not find `lifetime_demo` in `demo`

how import the mod file to test file?

1

There are 1 best solutions below

2
Peter Hall On

Tests in the tests directory, outside of the src directory are integration tests, which can only access your crate as a library, just as any end user of your library would. That means you need to import the crate in the tests and items are only accessible there if they are made public from the library, i.e. exported from lib.rs.

If you need to test private items or if your crate is not a library then put tests inside modules within the src directory instead.

Typically this is done within the same file as the code you are testing, e.g.:

// src/lifetime_demo/mod.rs

pub mod lifetime_mod {
    pub fn show() {}
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_trait() {
        lifetime_mod::show();
    }
}

If your project is a binary, not a library, then this will allow you to remove the lib.rs and just test the internals directly.