Welcome to the section on testing in Rust! Writing robust tests is a crucial part of software development, ensuring that your code behaves as expected. Rust provides a powerful and flexible testing framework built into its standard library, making it easy to write and run tests.
In this tutorial, you'll learn how to write unit tests, integration tests, and even benchmarks using Rust's built-in tools. By the end of this section, you should be comfortable writing and running tests in your Rust projects.
Rust's testing framework is designed to be simple yet powerful. It supports three types of tests:
Rust uses the #[test] attribute to mark functions as test cases. Here's a basic example:
1#[cfg(test)]2mod tests {3#[test]4fn it_works() {5assert_eq!(2 + 2, 4);6}7}
In this example:
#[cfg(test)] attribute tells the Rust compiler to include the module only when running tests.#[test] attribute marks the function as a test case.To run tests in your Rust project, use the following command:
$ cargo test
This command will compile your code and execute all functions marked with #[test]. If any test fails, it will display detailed information about the failure.
Let's dive into some practical examples to illustrate how to write different types of tests in Rust.
Here's an example of a unit test for a simple function:
1pub fn add(a: i32, b: i32) -> i32 {2a + b3}45#[cfg(test)]6mod tests {7use super::*;89#[test]10fn test_add() {11assert_eq!(add(2, 3), 5);12assert_ne!(add(1, 1), 0);13}14}
In this example:
add function takes two integers and returns their sum.test_add function tests the add function using assertions.Integration tests are placed in a separate directory called tests/. Here's an example:
tests/integration_test.rs:1use my_crate::add;23#[test]4fn test_add_integration() {5assert_eq!(add(5, 7), 12);6}
$ cargo test
Rust also supports benchmarking using the criterion crate. Here's how you can write a simple benchmark:
criterion to your Cargo.toml:1[dev-dependencies]2criterion = "0.3"
benches/bench.rs:1use criterion::{black_box, Criterion};2use my_crate::add;34fn add_benchmark(c: &mut Criterion) {5c.bench_function("add", |b| b.iter(|| add(black_box(1), black_box(2))));6}78criterion_group!(benches, add_benchmark);9criterion_main!(benches);
$ cargo bench
In this section, you learned how to write and run unit tests in Rust. In the next section, we'll explore more advanced testing techniques, including mocking and property-based testing.
Stay tuned for more insights into building robust applications with Rust!