Testing
101
Tests are identified by annotations:
Run them with:
Tests from docs
Code from the documentation is also executed by tests.
Making things testable
We need to timplement PartialEq
and Debug
. Usually is enough with annotation:
Macros
IMPORTANT: The assert macros accept additional parameters that are going to be passed to printf. Example: assert!(cond, "The user cond '{}' was supposed to be true", userId);
panic!(&str, &);
: runtime error equals test failure.
assert!(boolean);
: fails if provided argument is false.
assert_eq!<T>(T, T);
and assert_ne!<T>(T, T);
: fail if provided values are different or equal. They show the 2 values, so there are more convenient and that assert!
for this use case.
Testing for panic!
Add #[should_panic]
annotation to the test:
Tests returning Result<T, E>!
Tests can result Result<T, E>!
. This is useful for tests where we want to use the ? operator. It cannot be used with #[should_panic]
. If we want to check the Err, we need to use assert!(res.is_error())
.
Running tests
There are arguments before and after --
Running specific tests
Run the add_a_number
test:
Tests names are search patterns; run any tests that contains add
in the name:
#[ignore]
: Ignoring tests unless explicitly requested
Test Organization
Unit tests
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)
.
#[cfg(xxxxx)]
is an annotation that tells the compiler to only compile under a certain configuration option.
Integration tests
ONLY lib/
can be integration tested. This is why even binary crates have all the code in lib
and as little code as possible in src/main.rs
.
Create a tests directory next to
src
.Create rust files. The convention is ending with
_test.rs
.Add
#[test]
functions. No need for#[cfg(test)]
.
Each test is considered as a separate crate, so we need to bring our library into each test crate’s scope:
Shared code in tests
Only rust files that live in the tests
directory are considered integration tests:
Good for code shared by different tests.