Skip to main content
  1. šŸ“ Notes/

#learn-rust: tests

· loading ·

Syntax to write tests in Rust:

fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[cfg(test)]
mod add_function_tests {
    use super::*;

    #[test]
    fn add_works() {
        assert_eq!(add(1, 2), 3);
        assert_eq!(add(10, 12), 22);
        assert_eq!(add(5, -2), 3);
    }

    #[test]
    #[should_panic]
    fn add_fails() {
        assert_eq!(add(2, 2), 7);
    }

    #[test]
    #[ignore]
    fn add_negatives() {
        assert_eq!(add(-2, -2), -4)
    }
}

TheĀ cfgĀ attribute controls conditional compilation and will only compile the thing it’s attached to if the predicate isĀ true. TheĀ testĀ compilation flag is issued automatically by Cargo whenever we execute the commandĀ $ cargo test, so it will always be true when we run our tests. TheĀ use super::*;Ā declaration is necessary for the code inside theĀ add_function_testsĀ module to access theĀ addĀ in the outer module.



Christoph Voigt
Author
Christoph Voigt
A little bit about you