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