Tests

In Perl, we put our tests in a t directory and then prove -l will run them. Similarly, Rust has a tests directory and cargo test will run the tests there.

RustPerl
testst
cargo testprove -l
use testing;use Test::Most;

But Rust does this mostly for integration tests. Unit tests are typically put right in the same file as the code.

For example, I wrote a Perl module called Time::Moment::Epoch which converts a bunch of different epoch times to Time::Moment times. It has a bunch of unit tests in t/Time-Moment-Epoch.t.

I wrote a similar Rust crate called epochs, which converts those same epoch times to chrono::NaiveDateTime times. It has similar unit tests at the bottom of the library file itself.

The #[cfg(test)] macro tells cargo to run those tests when it is called as cargo test, but to ignore them when it is called as cargo build or cargo run.

Update (2024-05-15): I talked about testing at the Rust & C++ Cardiff book club. We are reading Rust for Rustaceans together and I did chapter 6. You can view my slides, some of which have links that I did not follow during the talk.