Welcome to our deep dive into Doc Tests in Rust! In this tutorial, we'll learn how to write unit tests and document your code effectively using Rust's built-in documentation features.
Doc Tests, also known as "documentation tests," are a powerful combination of unit tests and documentation in Rust. They allow you to test your code and provide clear, concise explanations of what each function does.
Doc Tests are essential for maintaining clean, readable, and maintainable code. They help:
To get started with Doc Tests, you need to have Rust installed on your system. If you haven't already, follow the official Rust installation guide.
Once you have Rust set up, you can create a new project using the cargo new command:
cargo new doc_test_practice
cd doc_test_practiceThis command creates a new Rust project called doc_test_practice.
Now that you have a project set up, let's write our first Doc Test! Open up src/lib.rs and replace its content with the following:
// 📝 Note: This is a simple example. In real-world projects, your functions will be more complex.
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
/// This is a doc comment. It describes the purpose and usage of the add function.
///
/// # Examples
///
/// ```
/// assert_eq!(add(1, 2), 3);
/// ```
pub fn run_tests() {
// Your tests go here
}Here, we've defined a simple add function and a run_tests function to call our tests. Notice the doc comment (///) that describes the add function and provides an example test.
To run your Doc Tests, add the following line at the end of src/lib.rs:
run_tests();Save the file, then run the project:
cargo runThis command will execute your run_tests function, which in turn will run the tests defined in the doc comments. If your tests pass, you'll see a success message; if not, you'll see the failing test cases.
Now that you understand how to write tests in doc comments, let's explore how to write traditional unit tests in Rust. Add the following test code within the run_tests function:
#[test]
fn test_add() {
assert_eq!(add(1, 2), 3);
}This test checks whether the add function returns the correct sum for the input 1 and 2. To run this test specifically, add the --test flag:
cargo test -- --test test_addWhat is the purpose of Doc Tests in Rust?
Happy coding! As you progress, feel free to explore more advanced Rust concepts and enjoy the journey of mastering this powerful language. 🚀