Run Unit Tests in Sub-Directories

My project's directory structure looks like:

.
├── Cargo.lock
├── Cargo.toml
├── LICENSE
├── README.md
├── docs
│   ├── CONTENTS.md
│   └── operations.md
├── src
│   ├── amusement_park.rs
│   ├── armstrong_number.rs
│   ├── collatz_conjecture.rs
│   ├── cone_volume.rs
│   ├── main.rs
...  ...

I'm able to run unit test for all files in src/ using cargo test --verbose.

All files except main.rs typically look like this and the main.rs file currently looks like:

mod amusement_park;
mod armstrong_number;
mod collatz_conjecture;
mod cone_volume;
...

There are many files in src/ and I have organized them in sub directories like common_concepts, control_flow, etc. But after doing this, I'm not able to run tests.

I tried changing main.rs to:

mod common_concepts::amusement_park;
mod common_concepts::armstrong_number;

mod control_flow:: collatz_conjecture;
mod control_flow:: cone_volume;

but can't get cargo test to work.

How can I run all unit tests in a subdirectory (src/common_concepts or src/control_flow) ?

You need to create a /src/lib.rs file and expose your common_concepts and control_flow modules through it.

You can read more about it here.

I'm able to get tests working by changing main.rs to:

mod common_concepts;
mod control_flow;

use common_concepts::amusement_park;
use common_concepts::armstrong_number;

use control_flow::collatz_conjecture;
use control_flow::cone_volume;

and adding mod.rs inside each sub-directory with names of other files. Example src/common_concepts/mod.rs looks like:

pub mod amusement_park;
pub mod armstrong_number;

Ah, interesting! Then the limitation applies only to integration tests.

I don't have integration tests. I'm learning Rust with unit tests and just wanted to organize files in src/ into sub-directories.

My previous post, shows an unused import warning in main.rs for use common_concepts::amusement_park; and other similar statements.

I better way to do this is to simply modify main.rs to:

mod common_concepts {
	mod amusement_park;
	mod armstrong_number;
}

mod control_flow {
	mod collatz_conjecture;
	mod cone_volume;
}

There is no mod.rs in any sub-directory and also no warnings.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.