Search code examples
unit-testingrustrust-cargo

Unit Tests not Compiling or Being found without mod tests in main.rs. Is this a requirement or am I missing some configuration?


In my main RS I have to declare mod tests; in the main.rs file for my unit tests to run. Coming from other languages, my startup file never has had to contain any information about the unit tests. Is this a standard in rust, or is there some configuration I am missing?

My file structure is as such:

src/
-- config/
-- models/
-- services/
-- tests/    <-- this is where my mod.rs for my tests are
main.rs

When running cargo test with a main including:

#[cfg(test)]
mod tests;

my unit tests are found, and they run.

If I remove the mod tests in main, running the same cargo test command does not run my unit tests.


Solution

  • In your case, cargo only cares about src/main.rs, so yes, you need to tell rust there is a mod called tests.

    Cargo has some special file/folders already, including a tests folder, but they need to be in the root of the project path.

    Per the Package Layout section of The Cargo Book,

    Integration tests go in the tests directory.

    Read more: