Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

24.7 Test Dependencies

Tests, examples, or benchmarks might require helper crates not needed by the main application or library code. These dependencies should be specified under the [dev-dependencies] section in your Cargo.toml file.

# Cargo.toml
[package]
name = "my_crate"
version = "0.1.0"
edition = "2021"

[dependencies]
# Regular dependencies used by src/lib.rs or src/main.rs
# Example: serde = { version = "1.0", features = ["derive"] }

[dev-dependencies]
# Dependencies only compiled for tests, examples, benchmarks
# Example: provides improved assertion diffs
pretty_assertions = "1.4"
# Example: helps create temporary files/directories for tests
tempfile = "3.10"

Cargo only compiles dev-dependencies when building targets that might need them (tests, examples, benchmarks). They are not included when a user depends on your library crate, nor are they included in release builds of binary crates unless explicitly used by src/main.rs (which is usually not the case).

Example using pretty_assertions: This popular dev-dependency provides replacements for assert_eq! and assert_ne! that produce colorful, detailed diff output when comparing complex structures, making failures much easier to diagnose.

// In src/lib.rs within #[cfg(test)] mod tests { ... }
// Or in a file within the tests/ directory

#[cfg(test)]
mod diff_tests {
    // Use the enhanced assertion macro from the dev-dependency
    use pretty_assertions::assert_eq;

    #[derive(Debug, PartialEq)]
    struct ComplexData {
        id: u32,
        name: String,
        values: Vec<i32>,
    }

    #[test]
    fn test_complex_data_equality() {
        let expected = ComplexData {
            id: 101,
            name: "Example".to_string(),
            values: vec![1, 2, 3, 4, 5],
        };
        let actual = ComplexData {
            id: 101,
            name: "Example".to_string(),
            values: vec![1, 2, 99, 4, 5], // Mismatch in the middle
        };

        // The standard assert_eq! would show the full structs.
        // pretty_assertions::assert_eq! shows a focused diff.
        assert_eq!(expected, actual);
    }
}