Unit and integration tests
Quick answer
Unit tests check small behaviors; integration tests check how public interfaces work together. Use both to catch regressions when changing code.
Organize tests around behavior
A function marked #[test] is discovered by the test harness. A module marked #[cfg(test)] is compiled for test builds. Integration tests in tests/ are separate crates and use the library's public API. In a scratch package named lesson_math, put the public function in src/lib.rs and the second example in tests/add.rs.
pub fn add(a: i32, b: i32) -> i32 { a + b }#[cfg(test)]mod tests { #[test] fn adds_negative() { assert_eq!(super::add(2, -3), -1); }}Manual local Rust/Cargo candidate; not executed. Expected behavior:
cargo test --lib: one passing test.The child module can test internal behavior too.
#[test]fn public_add() { assert_eq!(lesson_math::add(4, 5), 9); }Manual local Rust/Cargo candidate; not executed. Expected behavior:
cargo test --test add: one passing test in the configured package.The integration test calls the public interface as a consumer would.
Common mistake
A passing test is evidence for its cases, not proof of correctness for all inputs.
Try it yourself
Add a unit test for zero and an integration test for two negative numbers.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Unit and integration tests — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A test needs access to a private library helper. Where is it natural to put it?
Unit and integration tests — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust pub fn add(a: i32, b: i32) -> i32 { a + b } #[cfg(test)] mod tests { #[test] fn adds_negative() { assert_eq!(super::add(2, -3), -1); } } ``` Which outcome or interpretation best matches this example?
Unit and integration tests — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust #[test] fn public_add() { assert_eq!(lesson_math::add(4, 5), 9); } ``` Which outcome or interpretation best matches this example?