Custom matchers

Built-in matchers can only take you so far. Sometimes you need to write your own!

The Matcher trait

All matchers must implement the Matcher trait. There are two key methods you need to implement:

Optionally, you can also implement the explain_match method if you want to include further information derived from the actual and expected values in the failure message shown to the user.

Patterns

Most matchers in googletest follow the same pattern.
You define two items:

  • A struct which implements the Matcher trait ( e.g. EqMatcher)
  • A free function that returns an instance of the struct ( e.g. eq)

The free function is a convenience for the user since it results in terser assertions.
You can also choose to make the struct type private, returning impl Matcher from the free function instead (see anything as an example).

Exercise

The exercise for this section is located in 01_better_assertions/07_custom_matcher