rust / beginner
Snippet
Writing Basic Unit Tests
Tests live in modules marked with #[cfg(test)]. #[test] marks test functions that panic on failure. assert_eq! checks equality, assert! checks boolean conditions, #[should_panic] expects the test to fail. Use cargo test to run all tests.
snippet.rs
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
fn add(a: i32, b: i32) -> i32 {a + b}#[cfg(test)]mod tests {use super::*;#[test]fn test_basic_addition() {assert_eq!(add(2, 3), 5);assert_eq!(add(0, 0), 0);}#[test]#[should_panic]fn test_negative_numbers() {let result = add(-5, 3);assert!(result < 0);}#[test]fn test_commutative() {assert_eq!(add(3, 5), add(5, 3));}}
Breakdown
1
#[cfg(test)] mod tests {
Conditional compilation - only compiled during testing
2
use super::*;
Imports parent module items for testing
3
#[test] fn test_basic_addition() {
Test function marked with attribute
4
assert_eq!(add(2, 3), 5);
Asserts that actual equals expected value
5
#[should_panic]
Expects test to panic - marks expected failure