intermediateTesting
Tests with Result
Write tests that return Result<T, E>.
Tests with Result
Write tests that return Result
Difficulty
Intermediate
Code
rust
fn parse_number(s: &str) -> Result<i32, std::num::ParseIntError> {
s.parse::<i32>()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_valid() -> Result<(), String> {
let n = parse_number("42").map_err(|e| e.to_string())?;
if n != 42 {
return Err(format!("expected 42, got {}", n));
}
Ok(())
}
#[test]
fn test_parse_invalid() {
assert!(parse_number("abc").is_err());
}
#[test]
fn test_parse_negative() {
let n = parse_number("-5").unwrap();
assert_eq!(n, -5);
}
}
fn main() {
println!("Run with: cargo test");
}Explanation
Tests can return Result<(), E> for cleaner error handling.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the testing category to build a complete understanding of this topic.