Rust Learning Path — Chapter 20. Rust ships with testing support through Cargo, so there is no separate test framework required for the basics. This chapter covers unit tests, integration tests, documentation tests, assertions, expected failures, test organization and a production-friendly validation workflow.
1. Your first test
fn add(a: i32, b: i32) -> i32 { a + b } #[cfg(test)] mod tests { use super::*; #[test] fn adds_numbers() { assert_eq!(add(2, 3), 5); } }Run tests with:
cargo test2. Common assertions
assert!(value > 0); assert_eq!(actual, expected); assert_ne!(left, right);3. Custom assertion messages
assert!(port <= 65535, "invalid port: {port}");4. Testing panics
#[test] #[should_panic(expected = "invalid configuration")] fn rejects_bad_config() { panic!("invalid configuration"); }5. Tests can return Result
#[test] fn parses_port() -> Result<(), Box<dyn std::error::Error>> { let port: u16 = "8080".parse()?; assert_eq!(port, 8080); Ok(()) }6. Unit vs integration tests
Unit tests usually live beside the code they test. Integration tests live in the top-level tests/ directory and exercise the library through its public API.
my_app/ ├── src/ │ └── lib.rs └── tests/ └── api_tests.rs7. Test private implementation details carefully
Unit tests inside the same module can test private helpers, but prefer testing observable behavior instead of locking tests to every internal refactor.
8. Test filtering
cargo test user cargo test -- --show-output cargo test -- --test-threads=19. Ignored tests
#[test] #[ignore = "requires external database"] fn database_roundtrip() {}Run ignored tests explicitly:
cargo test -- --ignored10. Documentation tests
Rust code examples inside documentation comments can be compiled and tested:
/// Adds two integers. /// /// ``` /// assert_eq!(my_lib::add(2, 3), 5); /// ``` pub fn add(a: i32, b: i32) -> i32 { a + b }Run them as part of cargo test.
11. Testing error cases
fn parse_port(input: &str) -> Result<u16, String> { input.parse().map_err(|_| "invalid port".into()) } #[test] fn invalid_port_returns_error() { assert!(parse_port("abc").is_err()); }12. Arrange, Act, Assert
A simple structure keeps tests readable:
#[test] fn user_can_be_activated() { // Arrange let mut user = User::new("Ada"); // Act user.activate(); // Assert assert!(user.is_active()); }13. Test boundaries, not only happy paths
- Empty input
- Minimum and maximum values
- Malformed values
- Repeated operations
- Permission failures
- Timeout/error paths
14. A good local quality gate
cargo fmt --check cargo clippy --all-targets --all-features -- -D warnings cargo test --all-features cargo build --release15. Keep tests deterministic
Avoid relying on wall-clock timing, random external services or shared mutable global state unless the test intentionally covers those behaviors. Deterministic tests are easier to trust in CI.
16. Mini lab
Build a small configuration parser with successful and failing cases. Add unit tests for parsing helpers, integration tests for the public API, and one documentation example.
Key takeaways
Rust makes testing part of the normal Cargo workflow. Focus tests on behavior, cover failure paths, keep them deterministic and make formatting/linting/testing a repeatable quality gate.
Join the discussion
0 CommentsAsk questions, add context, or share what worked.
More from Melochip Editorial
Learn what Playwright testing is, why modern QA teams use it, how testers can get started, and the major types...
7 min read · Sep 19, 2026
Learn how Kubernetes Deployments and ReplicaSets work with practical YAML, scaling, self-healing, rolling upda...
7 min read · Sep 17, 2026
Learn Kubernetes security best practices with RBAC, Secrets, ServiceAccounts, Pod securityContext, NetworkPoli...
6 min read · Sep 17, 2026Related articles
Learn what Playwright testing is, why modern QA teams use it, how testers can get started, and the major types...
7 min read · Sep 19, 2026
Learn how Kubernetes Deployments and ReplicaSets work with practical YAML, scaling, self-healing, rolling upda...
7 min read · Sep 17, 2026
Learn Kubernetes security best practices with RBAC, Secrets, ServiceAccounts, Pod securityContext, NetworkPoli...
6 min read · Sep 17, 2026
Learn Kubernetes monitoring and logs with kubectl logs, events, metrics-server, top commands, Prometheus, Graf...
5 min read · Sep 17, 2026Stay in the loop. Get new Melochip articles
Receive Melochip article updates when new articles are available. Explicit opt-in only.
No comments yet. Start the discussion.