I'm quite confused by how Cargo finds tests to run.
I've created a Cargo project and it added a main.rs
for me. If I add #[test]
functions in there, they're found and run with cargo test
. If I add a foo.rs
file as a sibling to main.rs
and add tests in there, they're not found and run.
What subtlety am I missing? Do I somehow have to teach Cargo about new files?
Cargo can run your tests with the cargo test command. Cargo looks for tests to run in two places: in each of your src files and any tests in tests/ . Tests in your src files should be unit tests and documentation tests. Tests in tests/ should be integration-style tests.
The default behavior of the binary produced by cargo test is to run all the tests in parallel and capture output generated during test runs, preventing the output from being displayed and making it easier to read the output related to the test results.
You'll put unit tests in the src directory in each file with the code that they're testing. The convention is to create a module named tests in each file to contain the test functions and to annotate the module with cfg(test) .
Target Selection. When no target selection options are given, cargo test will build the following targets of the selected packages: lib — used to link with binaries, examples, integration tests, and doc tests. bins (only if integration tests are built and required features are available)
Cargo will not just compile any files that happen to be in your source directory. In order for Cargo to find a file, it must be referenced as a module either in main.rs
/lib.rs
or from some sub-module.
For example, in your main.rs
:
mod foo;
That's it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With