Unit Tests with Rust Tutorial 101
Writing unit tests is heavily integrated into rust without additional dependencies or external test runners. You can write unit tests inside the file that has the testable code or use a separate tests
directory, let's see how we do that.
You don't need to have any prior rust knowledge, but you will have to have rust installed, which most easily is done by using rustup.
Writing Your First Test
When creating a rust project with cargo new`` and we'll need a function that takes arguments and returns something, so let's go for a simple
sumfunction in
main.rs`:
fn sum(a: i32, b: i32) -> i32 {
return a + b;
}
fn main(){
println!("12 + 1 is {}", sum(12,1));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sum_test() {
assert_eq!(345+5, sum(345, 5));
}
}
Now for the interesting parts in the bottom of the file
#[cfg(test)]
the test section attribute (see conditional compilation)#[test]
the test attribute for the individual testassert_eq!
macro to compare the two values
This is the simplest way to implement a unit test in rust, the next step is to look at how to move your functions and tests into another separate file.
Running cargo test
should output something like:
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running target/debug/deps/rust_test_101-e2cf395340fbef91
running 1 test
test tests::sum_test ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Adding the following has the correct types, but it would cause the return value to be larger than i32
allows:
#[test]
#[should_panic]
fn greater_than_i32() {
sum(2147483647,1); // this would be bigger than i32 allows
}
By using #[should_panic]
we tell the test run to expect the following function to fail. This catches errors that usually crop up with:
thread 'main' panicked at 'attempt to add with overflow', src/main.rs:2:12
Now this is the easiest possible way to get started with writing tests in Rust, let me know if you want to know more in future posts! Don't forget to check out the Rust Book Chapter on Testing as well.