Mastering Rust
上QQ阅读APP看书,第一时间看更新

Running tests

The way we run this test is by compiling our code in test mode. The compiler ignores the compilation of test annotated functions unless it's told to build in test mode. This can be achieved by passing the --test flag to rustc when compiling the test code. Following that, tests can be run by simply executing the compiled binary. For the preceding test, we'll compile it in test mode by running this:

rustc --test first_unit_test.rs

With the --test flag, rustc puts a main function with some test harness code and invokes all your defined test functions as threads in parallel. All tests are run in parallel by default unless told to do so with the environment variable RUST_TEST_THREADS=1. This means that if we want to run the preceding test in single thread mode, we can execute with RUST_TEST_THREADS=1 ./first_unit_test.

Now, Cargo already has support for running tests, and all of this is usually done internally by invoking cargo test. This command compiles and runs the test annotated functions for us. In the examples that follow, we will mostly use Cargo to run our tests.