Skip to content

Custom assertions

You can make custom assertions by using the assert_custom!(...) macro. Let us look at an example:

// Instead of this:
let x = 3 + 5;
let y = 8;
assert_eq!(x, y);

// We can write this:
assert_custom!(
    "lhs == rhs",
    x == y,
    |panic_message_builder| {
        panic_message_builder
            .with_argument("lhs", "x", &x)
            .with_argument("rhs", "y", &y)
    }
)

Let's break it apart. There are three arguments to assert_custom!(...):

  • "lhs == rhs" - This is the assertion failure message, a description of what the assertion is trying to check for.
  • x == y - A boolean expression that is the assertion predicate. When this is true, the assertion passes. When it is false, the assertion panics.
  • |panic_message_builder| { ... } - A closure that configures the assertion's panic message to display detailed information about the assertion's arguments.

This allows you to make an assertion with any predicate and print any variables that are relevant.

Details (advanced)

The predicate expression must be of type bool.

Any arguments must implement the Debug trait.

Assertion Panic condition
assert_custom !predicate