Created
May 15, 2023 22:34
-
-
Save henryobiaraije/3caefcc814585b906c26f6f23a7142a9 to your computer and use it in GitHub Desktop.
Full Code - Basic Unit Testing in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let result1 = divide(4.0, 0.0); // Calling the divide function with arguments 4.0 and 0.0 and storing the result in result1. | |
println!("result1 is {:?}", result1); // Printing the value of result1 using debug formatting. | |
} | |
fn divide(a: f64, b: f64) -> Result<f64, String> { | |
if 0.0 == b { | |
return Result::Err("Hey, you can't divide by zero".to_string()); // Checking if b is equal to zero. If true, return an Err variant of the Result enum with an error message. | |
} | |
return Result::Ok(a / b); // If the condition is false, return an Ok variant of the Result enum with the result of dividing a by b. | |
} | |
#[cfg(test)] | |
mod test_mod { | |
use super::divide; // Importing the divide function from the outer scope. | |
#[test] | |
fn test_divide_2_values() { | |
let result1 = divide(4.0, 2.0); // Calling the divide function with arguments 4.0 and 2.0 and storing the result in result1. | |
assert_eq!(result1, Result::Ok(2.0)); // Asserting that the value of result1 is equal to an Ok variant of the Result enum with a value of 2.0. | |
} | |
#[test] | |
fn test_divide_by_zero() { | |
let result1 = divide(4.0, 0.0); // Calling the divide function with arguments 4.0 and 0.0 and storing the result in result1. | |
assert_eq!( | |
result1, | |
Result::Err("Hey, you can't divide by zero".to_string()) // Asserting that the value of result1 is equal to an Err variant of the Result enum with an error message. | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment