Organizing Tests
When you organize a backpack, you do not throw everything in one pocket β books in one spot, snacks in another. Tests like to be organized too! There are two main places they live. ποΈ
Unit tests: close to home
A unit is one small piece of your code, like a single function. Unit tests sit in
the same file as that code, tucked inside a little box called a mod tests. Above the
box you write #[cfg(test)].
That tag means βonly build this part when we are testing.β So your tests come along
during cargo test, but they do not get packed into the real program. Neat and clean! π§Ή
fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_adds() {
assert_eq!(add(2, 3), 5);
}
}
Integration tests: the big picture
Sometimes you want to test the whole model after it is built, not just one brick.
Those are integration tests, and they live in their own folder named tests/,
sitting next to your code folder.
Files in there test your program the same way a real user would β from the outside, pressing the buttons and checking the results.
#[cfg(test)];
integration tests get their own tests/ folder. Can you remember which is which?
Quick quiz
Where do integration tests live?
Right! Integration tests get their own tests/ folder and check everything working together. ποΈ
#[cfg(test)] mod tests
box, while integration tests live in a separate tests/ folder
and check the whole program. You have finished World 11 β great work checking your work! π