[Avg. reading time: 5 minutes]
Calculator with Unit Tests (Rust)
This example shows:
- functions (
add,sub,mul,div) - using
panic!for invalid input - unit tests with
#[test] #[should_panic]and#[ignore]
Copy this to VSCode
fn add(a: f32, b: f32) -> f32 { a + b } fn sub(a: f32, b: f32) -> f32 { if a < b { panic!("first value cannot be less than the second value"); } else { a - b } } #[allow(dead_code)] fn mul(a: f32, b: f32) -> f32 { a * b } #[allow(dead_code)] fn div(a: f32, b: f32) -> f32 { a / b } fn main() { let a: f32 = 17.0; let b: f32 = 33.0; let op = "-"; let result = if op == "+" { add(a, b) } else if op == "-" { sub(a, b) } else if op == "*" { mul(a, b) } else if op == "/" { div(a, b) } else { panic!("unsupported operator: {op}"); }; println!("{result}"); } #[cfg(test)] mod tests { use super::*; #[test] fn test_add() { assert_eq!(add(20.0, 10.0), 30.0); assert_eq!(add(10.0, 20.0), 30.0); result = add(1.0,2.0); assert_eq!(result,4,"Expected 3; returned result is {}", result); } #[test] #[should_panic(expected = "cannot be less")] fn test_sub_panics_when_a_less_than_b() { sub(10.0, 20.0); } #[test] fn test_sub_ok() { assert_eq!(sub(20.0, 10.0), 10.0); } #[test] #[ignore] fn test_sub_ignored_example() { assert_eq!(sub(20.0, 10.0), 10.0); } }
Other variations of asserts
- assert!
- assert_eq!
- assert_ne!
Run the script
cargo run
Run all tests
cargo test
Run ignored tests too
cargo test -- --ignored
Run specific test
cargo run sub
Show println output during tests
cargo test -- --nocapture
Run tests in specific thread
By default Rust uses multiple threads for speed.
cargo test -- --test-threads=1
Additional Links:
- Rust book testing chapter: https://doc.rust-lang.org/book/ch11-01-writing-tests.html
cargo testoptions: https://doc.rust-lang.org/cargo/commands/cargo-test.html