A test in Rust is a function that’s annotated with the test
attribute. To change a function into a test function, add #[test]
on the line before fn
. And then use cargo test
to run the tests, in which Rust builds a test runner binary of the annotated functions and reports.
assert!(condition)
- panic when condition is not trueassert_eq!(left, right)
- panic when left is not equal to rightassert_en!(left, right)
- panic when left is equal to rightWe can also add custom error message in assert!
macro by passing the message next to the condition.
If we know that a function should panic, we can add the attribute #[should_panic]
in the line before fn
and after #[test]
.
We can also make the tested function return a Result<T, E>
. And if the function returns an error type, the test fails. Otherwise, the test is passed.
By default, Rust would parallelize the tests when running. To make sure tests are running only by one thread, do cargo test -- --test-threads=1
cargo test -- --show-output
cargo test <pattern>
#[ignore]
cargo test -- --ignored