Running specific unit tests in Rust is a relatively straightforward process. Rust uses cargo as its build system and package manager, featuring a robust testing framework. Below, I'll walk you through how to run specific unit tests.
Step 1: Writing Unit Tests
First, you need to have unit tests written. In Rust, unit tests are typically written in the same file as your code, within a dedicated module marked with #[cfg(test)]. For example, suppose we have a function that calculates the sum of two numbers; we can write the test as follows:
rustpub fn add(a: i32, b: i32) -> i32 { a + b } #[cfg(test)] mod tests { use super::*; #[test] fn test_add() { assert_eq!(add(2, 2), 4); } }
Step 2: Running Specific Unit Tests
When dealing with multiple tests, you can run specific ones by specifying the test function name. This can be achieved by appending the test function name to the cargo test command. For instance, to run the test_add test from the previous example, you can use the following command:
bashcargo test test_add
This command will run all test functions whose names contain 'test_add'.
Advanced Usage: Filtering and Modules
If your tests are organized across different modules, you can target specific tests by specifying the module path. For example, if you have a module named math and test_add is within this module, you can run the test as follows:
rustmod math { #[test] fn test_add() { assert_eq!(super::add(2, 2), 4); } } // Run in command line cargo test math::test_add
This will accurately run the test_add test within the math module.
Conclusion
Running specific unit tests in Rust is simple and direct; by using cargo test with the test name, you can precisely control which tests are executed, which is especially useful for testing only modified sections in large projects.