Chapter 24: Testing in Rust

Testing is a fundamental aspect of software development. It ensures that your code behaves as intended, even after refactoring or adding new features. While Rust’s safety guarantees eliminate many memory-related issues at compile time, tests remain crucial for validating logic, performance, and user-visible functionality.

In this chapter, we’ll explore Rust’s various testing approaches, discuss how to organize and run tests, show how to handle test output and filter which tests are executed, and explain how to write documentation tests. We’ll also provide an overview of benchmarking techniques using nightly Rust or popular third-party crates. For a systems programming language, performance testing is especially important to ensure your programs meet their performance goals.

Rust offers a few main approaches to testing and benchmarking:

  • The nightly compiler includes a built-in benchmarking harness (still unstable).
  • Third-party crates like criterion and divan provide advanced benchmarking features and work on stable Rust.

At the end of this chapter, we provide concise examples for each benchmarking approach.