Learn Rust With Entirely Too Many Linked Lists
06

Testing

Tests live in the same file as the code they exercise, gated behind #[cfg(test)] so they vanish from release builds. cargo test finds them, compiles them, runs them, prints results. No separate harness, no CMake variant, no fixture wiring.

  1. A test module sits in the same file. #[cfg(test)] strips it from non-test builds. use super::* pulls the parent module's items into scope so the test can name the type without re-importing.
    #[cfg(test)]
    mod tests {
        use super::*;
    
        #[test]
        fn basics() {
            let mut list = List::new();
            assert_eq!(list.pop(), None);
    
            list.push(1);
            list.push(2);
            list.push(3);
            assert_eq!(list.pop(), Some(3));
            assert_eq!(list.pop(), Some(2));
    
            list.push(4);
            list.push(5);
            assert_eq!(list.pop(), Some(5));
            assert_eq!(list.pop(), Some(4));
            assert_eq!(list.pop(), Some(1));
            assert_eq!(list.pop(), None);
        }
    }
  2. cargo test runs every #[test] in parallel by default. Each test gets its own thread; failures don't cross-contaminate. --nocapture if you want to see println! from passing tests.
    $ cargo test
       Compiling lists v0.1.0
        Finished test [unoptimized + debuginfo] target(s) in 0.42s
         Running unittests src/lib.rs
    
    running 1 test
    test first::tests::basics ... ok
    
    test result: ok. 1 passed; 0 failed