🦀 Rust
Intermediate
How does unit testing and integration testing work in Rust?
Answer
Rust has first-class testing support. Unit tests live in the same file as the code they test, inside a module annotated with #[cfg(test)] so they are only compiled during cargo test. Mark test functions with #[test]. Use assert_eq!(a, b), assert_ne!(a, b), assert!(condition), or panic!() to fail a test. For tests expected to panic, use #[should_panic]. Integration tests live in a top-level tests/ directory, each file is compiled as a separate crate, and they can only access your crate's public API — testing the public interface as an external user would. Run all tests with cargo test, run a specific test with cargo test test_name, and run tests with output visible using cargo test -- --nocapture.
More Rust Questions
View all →- Intermediate How does error handling with the ? operator work in Rust?
- Intermediate What are the thiserror and anyhow crates for error handling?
- Intermediate What are trait objects (dyn Trait) in Rust?
- Intermediate What are generics in Rust and how do where clauses work?
- Intermediate What are Rust smart pointers?