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
fn main() {
let text = ;
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 = ;
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 = ;
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"))
}
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.