🦀 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.