πŸ§ͺ
World 11 Β· Checking Your Work

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. πŸ§ͺ

The Big Idea A test is a small piece of code whose only job is to ask: "Did my real code do the right thing?" If the answer is yes, the test passes. If not, it fails β€” so you know exactly what to fix.

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:

  1. Run your real code and grab what you got.
  2. 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.

Think of it like this… 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! πŸ™Œ

Ferris says: Tests are your friends. Once you write a good test, it keeps checking your code forever β€” even months from now when you change things. πŸ¦€
Try this! Change the test so it expects 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. πŸ§ͺ

You learned… A test checks that your code is correct. You mark it with #[test] and compare values using assert_eq!(got, expected). Next up: Running Tests β€” how to run all your checks at once! ▢️