Rust Tutorials: Understanding the `test` Attribute 🎯

beginner
18 min

Rust Tutorials: Understanding the test Attribute 🎯

Welcome to CodeYourCraft's in-depth guide on the test attribute in Rust! In this lesson, we'll explore how to write and run tests in your Rust projects.

Why Test? 💡

Testing is crucial for ensuring your code works as expected, especially when you're building complex systems. With Rust, we can write unit tests to check if our functions behave correctly in different scenarios.

What is the test Attribute? 📝

The test attribute is used to mark functions as test functions. These functions are automatically run when you execute the cargo test command.

rust
#[test] fn example_test() { // Test code here }

Writing Your First Test 🎯

Let's write a simple test function that checks if a function adds two numbers correctly.

rust
fn add_numbers(x: i32, y: i32) -> i32 { x + y } #[test] fn test_add_numbers() { let result = add_numbers(2, 3); assert_eq!(result, 5); }

In the example above, we define a function add_numbers that takes two integers and returns their sum. We then write a test function test_add_numbers that calls add_numbers with the arguments 2 and 3, and asserts that the result is equal to 5.

Running Tests 💡

You can run your tests using the cargo test command in your project's root directory. Rust will execute all the functions marked with the test attribute and print the results.

sh
$ cargo test Compiling my_project v0.1.0 (file:///path/to/my_project) Finished test [unoptimized + debuginfo] target(s) in 0.31s Running tests my_project-test... running 1 test test my_project-test::test_add_numbers ... ok Test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s

Pro Tip: 💡

You can use the assert! macro to check if a condition is true. If the condition is false, the test will fail.

rust
#[test] fn test_add_numbers() { let result = add_numbers(2, 3); assert_eq!(result, 5); assert!(result > 0); }

Quiz 📝

Quick Quiz
Question 1 of 1

Which attribute marks a function as a test function in Rust?

Summary ✅

In this lesson, we learned about the test attribute in Rust, which allows us to write and run tests for our functions. By writing tests, we can ensure our code works as intended and catch any issues early in the development process.

Stay tuned for more Rust tutorials on CodeYourCraft! 🌟