Member-only story

Mastering Rust Testing: A Complete Guide from Basic Use Cases to Controlling Test Execution

Beck Moulton
3 min readApr 22, 2024

--

Mastering Rust Testing: A Complete Guide from Basic Use Cases to Controlling Test Execution

Rust, as a system programming language, emphasizes reliability in multiple aspects, one of which is testing. Rust language not only comes with a powerful testing framework, but also encourages developers to write and run tests in daily development. In this article, we will introduce in detail how to write and control tests in Rust, helping you improve code quality and stability.

Writing test functions

When using Cargo to create a Rust package for the lib category, Cargo will automatically generate a test module for us. Here is a simple test example:

#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}

The test function needs to be marked with the #[test]attribute. In the test function, the assert_eq!macro is used for result assertion to verify that the code being tested meets expectations.

Run tests with cargo test

To run all tests, simply run the following command in the project root directory:

$ cargo test

When there are many test cases, you may want to run only part of the tests or perform specific controls on the output results…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet