This is a workshop about testing in Rust. It is intended for people who are already a bit familiar with Rust and want to learn more about testing in Rust.
- Basic knowledge of Rust.
- A working Rust installation. (See https://rustup.rs/)
- A working Rust IDE (e.g. Visual Studio Code with the Rust extension) or an editor.
Open the slides to follow along with the workshop.
Go to the src/exercises
module and follow the instructions there.
You can start with basic.rs
and then move on to more advanced exercises.
This workshop is about testing in Rust. We will cover the following topics:
- Writing unit tests in the same file as the code
- Returning
Result
from tests - Keep tests close to the code
- Writing integration tests
- Integration tests vs functional tests
- Doctests
- Test doubles
- Mocks
- Traits
- Tips and tricks
- You can return
Result
from tests #[ignore]
attribute- Testing panics
#[should_panic]
#[cfg(test)]
for convenience methods
- You can return
- Test isolation
- Isolating the filesystem:
tempdir
- Isolating the network: HTTP mocking
- Isolating external dependencies:
mockall
- Isolating the filesystem:
- Speeding up tests
- Unit tests over integration tests
- Faster integration tests: use a single compilation unit
- cargo test runs tests in parallel
- cargo nextest
- sequential tests with
--test-threads=1
or https://crates.io/crates/serial_test
- Exploratory testing
- Property-based testing
- Mutation testing
- Benchmark tests
- Structuring code for better testing Onion Architecture / Hexagonal Architecture
- Test coverage:
cargo tarpaulin --out Html
If you want to run unit tests only, you can use the --lib
flag:
cargo test --lib
To run only the integration tests, you can use the --test
flag:
cargo test --test '*'
To run a specific test, you can use the --test
flag with the test name:
cargo test --test fibonacci_is_prime
- cargo-nextest: A faster test runner for Rust.
- quickcheck: Automated property-based testing with shrinking support.
- proptest: Another property-based testing library.
- loom: a testing tool for concurrent code, which runs a test many times, permuting the possible concurrent executions.
- mockall: Trait-based mocking library.
- mockito: HTTP mocking library.
- httpmock: Another HTTP mocking library.
- assert_cmd: Test command line applications.
- tempfile: Create temporary files and directories.
- insta: Snapshot testing library.
- fakeit: Fake data generator library with 130+ functions.
- test-context: A library for writing tests with setup and teardown functions.
- embedded-test: A test harness and runner for embedded devices
- pretty_assertions: Alternative to
assert_eq!
with better diffing and color support. - assertor: Fluent assertion library for Rust with readable messages.
- trybuild: Testing procedural macros.