Real Projects · 16 min · free with an account

Testing

Lesson preview · about 30%

Tests turn behaviour into executable evidence.

Core idea

#[cfg(test)] keeps test code out of the release build entirely.

Start with the idea

#[test] functions are compiled only for the test harness, so they cost nothing in a release build. Unit tests sit beside the code and can reach its private details; integration tests live in tests/ and see only the public API, which is a useful check on your own interface.

A test records an observable promise. #[test] marks a function that the test harness runs under cargo test; an assertion compares the actual value with a prediction. The sample puts tests beside the implementation in a #[cfg(test)] module, which is a good place for small unit tests of edge cases and private helpers. The module is only compiled when testing, so it does not become a normal production code path.

Start with a function that adds two numbers.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Cargo & Real Projects