Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cargo not running tests in top-level file

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?

like image 811
tenpn Avatar asked Jul 02 '17 17:07

tenpn


People also ask

How do you run a cargo test?

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.

Does cargo run tests in parallel?

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.

Where do I place unit tests in Rust?

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) .

Does cargo test also build?

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)


1 Answers

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.

like image 126
Peter Hall Avatar answered Oct 05 '22 22:10

Peter Hall