capypad
0 day streak
rust / beginner
Snippet

Writing Your First Unit Test

The #[test] attribute marks a function as a test. assert_eq! checks that two values are equal. Tests run with cargo test and verify your code works correctly.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fn add(a: i32, b: i32) -> i32 {
a + b
}
 
#[test]
fn test_add_positive() {
assert_eq!(add(2, 3), 5);
}
 
#[test]
fn test_add_negative() {
assert_eq!(add(-1, -1), -2);
}
 
fn main() {
println!("Testing add function");
}
Breakdown
1
#[test]
Marks this function as a test to be run
2
assert_eq!(add(2, 3), 5);
Asserts that add(2, 3) equals 5
3
cargo test
Command to run all tests in the project