Writing Tests
When you finish a math problem, do you check your answer before moving on? A test in Rust is exactly that β a small check that makes sure your code gives the right answer. π§ͺ
Marking something as a test
To tell Rust βhey, this is a test,β you write a special tag on the line above it:
#[test]. That tag is like a sticky note that says βcheck me!β π
Inside the test you do two things:
- Run your real code and grab what you got.
- Compare it to what you expected with
assert_eq!(got, expected).
The name assert_eq! means βassert these are equalβ β it shouts if the two
values do not match.
assert_eq! is like marking your own work against an answer key. You say,
"My answer is 4." The key says: "The right answer is 4 β correct! β
" If you had said
5, you would spot the mismatch right away. π΄
Testing a tiny add function
Here is an add function and a test that checks it. Press βΆ Run to see it work!
The #[test] part does not run when you press Run β it runs when you type
cargo test. When you do, Rust checks your test and prints something like this:
running 1 test
test it_adds ... ok
test result: ok. 1 passed; 0 failed
That little ok means your code passed the check. Nicely done! π
6 instead of 5. Now the numbers
do not match β that is a failing test! Then change it back to 5
to make it pass again.
Quick quiz
What does assert_eq!(got, expected) do?
Yes! assert_eq! compares what you got to what you expected, just like checking your answer against the key. π§ͺ
#[test] and compare values using assert_eq!(got, expected).
Next up: Running Tests β how to run all your checks at once! βΆοΈ