Writing Automated Tests
7 min read
Writing Automated Tests in Rust 🦀
Welcome to the wonderful world of automated testing in Rust! You might be thinking, "Tests? Isn't that what interns are for?" Well, while that's one approach, writing automated tests is like having a tiny, meticulous robot that checks your work for you, 24/7. It’s a crucial practice in modern software development that ensures your code does what you expect it to do, even as you add new features or refactor existing ones.
The Problem: Imagine you've built a beautiful, complex machine. Every time you add a new gear or tighten a bolt, you have to manually check every single other part of the machine to make sure you didn't break something. This is slow, tedious, and prone to human error.
The Solution: Automated tests are like a set of diagnostic tools you build for your machine. With the press of a button, you can run all your checks and be confident that everything is still in working order. In Rust, the testing framework is a first-class citizen, built right into the language and its tooling.
How to Write Tests in Rust 🧪
Writing tests in Rust is surprisingly straightforward. Let's start with the basics.
Definition: A test in Rust is a function that's annotated with the #[test] attribute. This attribute tells the Rust compiler to treat this function as a test case.
The Anatomy of a Test Function
At its core, a test function in Rust does three things:
- Arrange: Set up any necessary data or state.
- Act: Run the code you want to test.
- Assert: Check that the results are what you expect.
Let's create a new library project to see this in action:
cargo new adder --lib
cd adderCargo has already generated a basic library file and a test for us in src/lib.rs. Let's take a look:
// src/lib.rs
pub fn add(left: usize, right: usize) -> usize {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}Let's break this down:
#[cfg(test)]: This is a conditional compilation attribute. It tells the Rust compiler to only compile thetestsmodule when we're running tests (e.g., withcargo test). This keeps our test code out of our final production binary.mod tests: We create a module namedteststo hold our test functions. This is a common convention.use super::*;: This line brings all the items from the parent module (our library code) into the scope of thetestsmodule.#[test]: This attribute marks theit_worksfunction as a test.assert_eq!(result, 4);: This is an assertion macro. It checks if two values are equal. If they are, the test passes. If not, the test panics and fails.
To run the tests, simply execute:
cargo testYou should see output indicating that one test has passed.
Essential Assertion Macros
Rust's standard library provides a few handy macros for making assertions in your tests:
assert!(expression): This macro panics if theexpressionevaluates tofalse. It's great for checking fortrueconditions.assert_eq!(left, right): As we've seen, this checks for equality.assert_ne!(left, right): This is the opposite ofassert_eq!; it checks for inequality.
These macros can also take an optional custom message to be printed if the assertion fails, which can be very helpful for debugging.
#[test]
fn another() {
// This test will fail
assert_eq!(5, 6, "Five and six are not the same, who knew?");
}Testing for Panics with should_panic
Sometimes, you want to ensure your code panics when it's supposed to (e.g., when given invalid input). For this, you can use the #[should_panic] attribute.
pub struct Guess {
value: i32,
}
impl Guess {
pub fn new(value: i32) -> Guess {
if value < 1 || value > 100 {
panic!("Guess value must be between 1 and 100, got {}.", value);
}
Guess { value }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic]
fn greater_than_100() {
Guess::new(200);
}
}The greater_than_100 test will pass if the code inside it panics. If it doesn't panic, the test will fail.
To be more precise, you can also provide an expected message to should_panic. This ensures the test only passes if the panic message contains the specified text.
#[test]
#[should_panic(expected = "Guess value must be between 1 and 100")]
fn greater_than_100_with_message() {
Guess::new(200);
}Controlling How Tests are Run
As your project grows, you'll likely accumulate a lot of tests. cargo test comes with a set of command-line options to help you manage and run them effectively.
Here are some of the most frequently used commands:
- Running a specific test: You can run a single test by providing its name.bash
cargo test it_works - Running tests in a module: You can run all the tests within a specific module.bash
cargo test tests:: - Ignoring tests: Sometimes you might have tests that are slow or not yet complete. You can mark them with the
#[ignore]attribute.By default, ignored tests are skipped. You can run them explicitly with:rust#[test] #[ignore] fn expensive_test() { // ... takes a long time to run }bashcargo test -- --ignored - Running tests sequentially: By default,
cargo testruns your tests in parallel using multiple threads. This is generally faster, but if your tests interfere with each other (e.g., they modify the same file or a database), you might need to run them one at a time.bashcargo test -- --test-threads=1 - Showing output from tests: By default, the output of passing tests (like
println!) is hidden. To see it, you can use the--show-outputflag.bashcargo test -- --show-output
Test Organization: Unit Tests vs. Integration Tests
In Rust, tests are typically categorized into two types: unit tests and integration tests.
Unit Tests
Definition: Unit tests are designed to test a small, isolated piece of code, like a single function. They are usually placed in the same file as the code they are testing, inside a tests module.
Key Characteristics:
- Small and focused.
- Can access private functions and modules within the same crate.
- Fast to run.
The adder example we've been using contains a unit test.
Integration Tests
Definition: Integration tests are for testing how different parts of your library work together, or for testing the public API of your library as a whole.
Key Characteristics:
- They live in a separate directory called
testsat the root of your project, next to thesrcdirectory. - Each file in the
testsdirectory is compiled as a separate crate. - They can only call the public functions of your library.
Let's add an integration test to our adder project.
First, create a tests directory:
mkdir testsNow, create a new file tests/integration_test.rs:
// tests/integration_test.rs
use adder; // Import our library crate
#[test]
fn it_adds_two() {
assert_eq!(4, adder::add(2, 2));
}Now, when you run cargo test, it will run both your unit tests and your integration tests.
A fun fact: You can have subdirectories within your tests directory to further organize your integration tests. Cargo will look for tests in any .rs files inside the tests directory and its subdirectories.
Documenting Code with rustdoc and Doc-tests
Rust has a fantastic tool called rustdoc that generates documentation from your code comments. What's even cooler is that you can embed runnable code examples directly in your documentation, and cargo test will run them as tests!
Definition: Documentation tests (or doc-tests) are code examples written within your documentation comments that are also run as tests.
To write a documentation comment, you use /// instead of //.
Let's add some documentation with a test to our add function in src/lib.rs:
// src/lib.rs
/// Adds two numbers together.
///
/// # Examples
///
/// ```
/// let result = adder::add(2, 2);
/// assert_eq!(result, 4);
/// ```
pub fn add(left: usize, right: usize) -> usize {
left + right
}Now, when you run cargo test, it will also run the code inside the ``` block in the documentation.
To generate the HTML documentation, you can run:
cargo doc --openThis will build the documentation and open it in your web browser. You'll see your add function beautifully documented, complete with the example. This is an incredibly powerful way to ensure your examples in the documentation are always correct and up-to-date.
References for Extra Reading
Challenge
Challenge: Implement a Comprehensive Test Suite
You are given a shapes module containing a Rectangle struct with a few methods. Your task is to write a complete unit test suite for this module within the same file, following Rust's testing conventions.
Requirements:
- Create a test module named
testsinside theshapesmodule. - This test module must only be compiled when running tests.
- Inside the test module, bring all items from the parent
shapesmodule into scope. - Write a test function
calculates_areathat verifies theareamethod works correctly for a rectangle of width 8 and height 7. - Write a test function
larger_can_hold_smallerthat creates two rectangles and asserts that the larger one can hold the smaller one. - Write a test function
smaller_cannot_hold_largerthat asserts a smaller rectangle cannot hold a larger one. If this test fails, it should display the custom message:"Smaller rectangle should not be able to hold a larger one." - The
newfunction is designed to panic if either dimension is zero. Write a testpanics_on_zero_widththat confirms a panic occurs when creating a rectangle with a width of 0. The test should specifically check that the panic message contains the substring"must be non-zero". - Add a documentation test to the
can_holdmethod. This example should demonstrate a case where one rectangle can hold another. - Finally, add an
#[ignore]attribute to thelarger_can_hold_smallertest, marking it as a test to be skipped during a normalcargo testrun.
Expected result
Your solution should be a single block of code containing the shapes module. Inside this module, there should be a mod tests block annotated with #[cfg(test)]. This test module must contain five test functions, each annotated correctly:
calculates_area: usesassert_eq!to check the area.larger_can_hold_smaller: usesassert!and is annotated with#[test]and#[ignore].smaller_cannot_hold_larger: usesassert!with a custom failure message string.panics_on_zero_width: is annotated with#[should_panic(expected = "must be non-zero")].
Additionally, the can_hold method in the impl Rectangle block must be preceded by a documentation comment (///) containing a runnable code example that uses an assert!.