liveBook · Manning

Assert_eq

As explained in Refactoring to Rust

The Rust assert_eq! macro compares two values for equality and panics when they differ.

The Rust assert_eq! macro compares two values for equality and panics when they differ. In tests, the framework catches that panic, marks the test as failed, and reports both values using their Debug representations. section 7.1

A passing equality assertion

let result = 2 + 2; assert_eq!(result, 4); section 7.1

A failing equality assertion

let result = 2 + 2; assert_eq!(result, 5); The test output reports an assertion failure with left: 4 and right: 5, then marks the test as failed.

Use assert_eq! alongside the surrounding Rust testing tools:

  • Place assertions in functions marked with #[test]. section 7.1
  • Run tests with cargo test; use -- --nocapture when test output must be displayed. section 7.3
  • Use assert! for Boolean conditions, or unwrap() and expect() when merely validating that an operation does not return an error. section 7.1

How Refactoring to Rust covers it

How deep it goes
Explains comparison, panic behavior, captured failures, and Debug output, but does not cover macro internals.
Examples
Demonstrates 2 + 2 equaling 4, deliberately failing against 5, and inspecting output from passing and failing tests.
What it assumes
Builds from a test function, #[test] attribute, computed value, and expected value.
What you can do after
Apply it via Rust’s test framework to compare values and diagnose failures from reported left and right values.
How it connects
Connects equality assertions with unit tests, test functions, assert!, unwrap(), expect(), and cargo test.

Also explained in

Compare how 2 books explain assert_eq →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.