Rust Unit Testing

Usage

add #[test] on the line before fn. When you run your tests with the cargo test command, Rust builds a test runner binary that runs the functions annotated with the test attribute and reports on whether each test function passes or fails.

the#[ignore] attribute to exclude some tests

Cargo Command

1
2
3
4
5
cargo test

cargo test tset_case_name

cargo test prefix_test_name

Example

Case: Hello

1
2
3
4
5
6
7
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
1
2
3
4
running 1 test
test tests::it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

panic

1
2
3
4
5
6
7
8
9
10
11
12
#[cfg(test)]
mod tests {
#[test]
fn exploration() {
assert_eq!(2 + 2, 4);
}

#[test]
fn another() {
panic!("Make this test fail");
}
}

should panic

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
pub fn divide_non_zero_result(a: u32, b: u32) -> u32 {
if b == 0 {
panic!("Divide-by-zero error");
} else if a < b {
panic!("Divide result is zero");
}
a / b
}

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

#[test]
fn test_divide() {
assert_eq!(divide_non_zero_result(10, 2), 5);
}

#[test]
#[should_panic]
fn test_any_panic() {
divide_non_zero_result(1, 0);
}

#[test]
#[should_panic(expected = "Divide result is zero")]
fn test_specific_panic() {
divide_non_zero_result(1, 10);
}
}