Testing Rust Projects
Result Assertion
Check Success Paths
Result-returning helpers are easy to test by asserting that a parse succeeded before unwrapping the value.
Program
Play the program to choose numeric input and verify the success path before printing the parsed count.
result_assertion.rs
Replay: real traced execution (multi-file project)
fn main() {
let text = "4";
let result = parse_count(text);
assert!(result.is_ok());
let count = result.unwrap();
println!("{count}");
}
fn parse_count(text: &str) -> Result<i32, String> {
text.parse::<i32>().map_err(|_| String::from("not a number"))
}
fn main() {
let text = "7";
let result = parse_count(text);
assert!(result.is_ok());
let count = result.unwrap();
println!("{count}");
}
fn parse_count(text: &str) -> Result<i32, String> {
text.parse::<i32>().map_err(|_| String::from("not a number"))
}
fn main() {
let text = "10";
let result = parse_count(text);
assert!(result.is_ok());
let count = result.unwrap();
println!("{count}");
}
fn parse_count(text: &str) -> Result<i32, String> {
text.parse::<i32>().map_err(|_| String::from("not a number"))
}
text ← "4"
1fn main() {2 let tex→ "4"t = "4"; //@text="4", "7", "10"3 let result = parse_count(tex"4"t);4 assert!(result.is_ok());result ← Ok(4), count ← 4
2 let text = "4"; //@text="4", "7", "10"3 let resul→ Ok(4)t = parse_count(tex"4"t);4 assert!(result.is_ok());5 let coun→ 4t = result.unwrap();6 println!("{count}");7}output4
text ← "7"
1fn main() {2 let tex→ "7"t = "7";3 let result = parse_count(tex"7"t);4 assert!(result.is_ok());result ← Ok(7), count ← 7
2 let text = "7";3 let resul→ Ok(7)t = parse_count(tex"7"t);4 assert!(result.is_ok());5 let coun→ 7t = result.unwrap();6 println!("{count}");7}output7
text ← "10"
1fn main() {2 let tex→ "10"t = "10";3 let result = parse_count(tex"10"t);4 assert!(result.is_ok());result ← Ok(10), count ← 10
2 let text = "10";3 let resul→ Ok(10)t = parse_count(tex"10"t);4 assert!(result.is_ok());5 let coun→ 10t = result.unwrap();6 println!("{count}");7}output10
Result
`Result<T, E>` makes success and failure explicit.
assert!
`assert!(result.is_ok())` checks the success condition before unwrapping.
unwrap
`unwrap` is safe here because the assertion already checked this controlled input.