Skip to main content
Module 9 · Lesson 3 of 320/24 in the course~18 min
Module lessons (3/3)

Unit Test #[cfg(test)], assert! and Test with Result

Lesson preview5 hands-on exercises readyCourse Rust · Module 9 — Modules, Cargo and Testing

Write module unit tests #[cfg(test)], descriptive assertions assert_eq!, #[should_panic], integration tests and doc-tests.

What you'll learn in this lesson

  • Write isolated unit test suites in the same source file thanks to #[cfg(test)] mod tests.
  • Choose between assert!, assert_eq!, assert_ne! and the #[should_panic(expected = "...")] attribute.
  • Use tests that return Result<(), E> to combine assertions and the ? operator.

Overview

Rust includes a lightning-fast native test runner that can be launched with cargo test, including parallel execution on separate threads and conditional compilation so that zero test code burdens the final build.

In Rust the unit tests live in the same file as the tested code inside a mod tests module annotated with #[cfg(test)]: thanks to use super::*; they also access private functions!

Sections covered in this lesson

  1. 11. Anatomy of a module #[cfg(test)]
  2. 22. Check for intentional panics with #[should_panic]
  3. 33. Tests returning Result<(), E>
  4. 44. Integration tests and automatic Doc-Tests
  5. 5Practical exercises
  6. 6Check for understanding
Pro Lesson · Module 9 — Modules, Cargo and Testing

Unlock "Unit Test #[cfg(test)], assert! and Test with Result" and the full Course Rust curriculum

Write module unit tests `#[cfg(test)]`, descriptive assertions `assert_eq!`, `#[should_panic]`, integration tests and doc-tests.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course Rust plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.