assert!, assert_eq!, and assert_ne! in testsshould_panicTests ensure code functions as expected
Rust (cargo) provides native support for automating tests
Types of test in Rust include:
Annotate functions with #[test] to make them tests
Run tests with cargo test
assert! MacroEnsures a condition evaluates to true
Example:
assert_eq! and assert_ne! Macrosassert_eq!(left, right) checks left == right
assert_ne!(left, right) checks left != right
Provide detailed error messages on failure
Example:
Add custom messages to assertions
Example:
should_panicUse #[should_panic] to test code that should panic
Use expected to specify a substring of the panic message
Result<T, E> in TestsTests can return Result<T, E> instead of panicking
Allows use of the ? operator in tests
Tests run in parallel by default
To run tests consecutively:
Output from println! is captured by default
To display output even for passing tests:
Run a specific test by specifying its name:
Run tests matching a pattern:
Use #[ignore] to exclude tests by default
Run ignored tests with:
#[cfg(test)]Place tests in a tests module annotated with #[cfg(test)]
This module is only compiled when testing
You can test private functions in Rust
Example:
Test the public API as an external user would
Placed in the tests directory
Each file in tests is a separate crate
my_project
├── Cargo.toml
├── src
│ └── lib.rs
└── tests
└── integration_test.rsExample:
Share code between integration tests using modules
Create tests/common/mod.rs for shared code
main.rs) can’t be tested directly via integration testslib.rs)main.rs can then call into lib.rs