How to Use Predicate Assertions in GoogleTest for Better Error Messages
GoogleTest predicate assertions evaluate custom Boolean predicates while automatically generating detailed failure messages that include both the expression strings and actual runtime values of the arguments.
The google/googletest framework provides predicate assertion macros that replace opaque EXPECT_TRUE calls with self-diagnosing tests. Unlike basic assertions, these utilities capture the expression text and argument values, emitting precise failure diagnostics that show exactly why a custom validation rule failed.
Understanding Predicate Assertion Macros
The predicate assertion machinery lives in googletest/include/gtest/gtest_pred_impl.h, which defines two families of macros: EXPECT_PREDn for simple predicates and EXPECT_PRED_FORMATn for custom formatters. These macros support one through five arguments.
EXPECT_PREDn wraps a plain Boolean function. When the predicate returns false, GoogleTest prints the expression and evaluates to false, but cannot describe the specific values involved beyond what the default formatter extracts.
EXPECT_PRED_FORMATn accepts a predicate-format function that you write. This function receives stringified expressions followed by the actual values, letting you embed the runtime data directly into the failure message via ::testing::AssertionResult.
The public header googletest/include/gtest/gtest.h re-exports these macros, so including gtest/gtest.h is sufficient for most user code.
Writing Custom Predicate-Format Functions
A predicate-format function must match the signature pattern used by the macro size you need. For a single argument, the signature is:
::testing::AssertionResult FunctionName(const char* expr1, const T1& v1);
For multiple arguments, the expression strings precede the values in order:
::testing::AssertionResult FunctionName(const char* expr1, const char* expr2,
const T1& v1, const T2& v2);
The function returns ::testing::AssertionSuccess() on pass, or ::testing::AssertionFailure() << "message" on fail. The AssertionResult class is defined in googletest/include/gtest/gtest-assertion-result.h, which provides the stream insertion operator for building custom diagnostics.
Because the macro forwards the original source expressions as the initial const char* parameters, your failure message can quote the exact code that was evaluated alongside the computed values.
GoogleTest Predicate Assertion Examples
Single-Argument Predicates with EXPECT_PRED1
Use EXPECT_PRED1 when a simple Boolean function validates one value. The default formatter prints the predicate call and the Boolean result.
// Predicate function
bool IsEven(int n) { return n % 2 == 0; }
TEST(MathTest, EvenCheck) {
int x = 3;
EXPECT_PRED1(IsEven, x);
}
Failure output:
Value of: IsEven(x)
Actual: false
Expected: true
Multi-Argument Predicates with EXPECT_PRED2 and EXPECT_PRED3
For predicates requiring multiple inputs, use EXPECT_PRED2, EXPECT_PRED3, EXPECT_PRED4, or EXPECT_PRED5 according to the argument count.
bool InRange(int value, int low, int high) {
return low <= value && value <= high;
}
TEST(RangeTest, SimpleBounds) {
EXPECT_PRED3(InRange, 5, 1, 10); // Checks 5 ∈ [1,10]
}
If the check fails, the message displays the full invocation, though the default formatter does not expand the individual bound values.
Custom Formatters for Detailed Failure Messages
To expose the actual numeric values that violated the rule, implement a predicate-format function and invoke it with EXPECT_PRED_FORMAT1, EXPECT_PRED_FORMAT2, or the variant matching your argument count.
::testing::AssertionResult IsEvenFormat(const char* expr, int n) {
if (n % 2 == 0) return ::testing::AssertionSuccess();
return ::testing::AssertionFailure()
<< expr << " is " << n << ", which is not even";
}
TEST(MathTest, EvenCheckVerbose) {
int x = 3;
EXPECT_PRED_FORMAT1(IsEvenFormat, x);
}
Failure output:
x is 3, which is not even
For three arguments, the pattern expands accordingly:
::testing::AssertionResult InRangeFormat(const char* expr_val,
const char* expr_low,
const char* expr_high,
int value,
int low,
int high) {
if (low <= value && value <= high) return ::testing::AssertionSuccess();
return ::testing::AssertionFailure()
<< value << " is outside the range [" << low << ", " << high << "]";
}
TEST(RangeTest, VerboseBounds) {
EXPECT_PRED_FORMAT3(InRangeFormat, 20, 1, 10);
}
Working with User-Defined Types
Predicate assertions work with any CopyConstructible type. GoogleTest prints the value using its default printer or your custom operator<< overload.
struct Point { int x, y; };
bool IsOrigin(const Point& p) { return p.x == 0 && p.y == 0; }
TEST(PointTest, OriginCheck) {
Point p{3, 4};
EXPECT_PRED1(IsOrigin, p);
}
If p is not the origin, the failure message includes the pretty-printed Point representation alongside the expression IsOrigin(p).
Summary
- Predicate assertions (
EXPECT_PREDnandEXPECT_PRED_FORMATn) provide richer diagnostics thanEXPECT_TRUEfor custom validation logic. - Macro definitions reside in
googletest/include/gtest/gtest_pred_impl.hand support one through five arguments. - Custom formatters receive both expression strings and value references, enabling failure messages that state exactly which values violated the predicate.
- AssertionResult (from
gtest-assertion-result.h) providesAssertionSuccess()andAssertionFailure()for constructing formatter return values. - User-defined types integrate seamlessly; define
operator<<to control how values appear in failure logs.
Frequently Asked Questions
What is the difference between EXPECT_PRED1 and EXPECT_PRED_FORMAT1?
EXPECT_PRED1 accepts a simple Boolean predicate and uses a default formatter that prints the expression and the Boolean result. EXPECT_PRED_FORMAT1 accepts a function returning ::testing::AssertionResult that receives the expression string and the value, letting you embed the actual data into the failure message rather than just printing true or false.
How many arguments can a GoogleTest predicate assertion handle?
GoogleTest defines predicate macros for one through five arguments: EXPECT_PRED1 through EXPECT_PRED5 and EXPECT_PRED_FORMAT1 through EXPECT_PRED_FORMAT5. The implementation in gtest_pred_impl.h generates these variants using preprocessor repetition to maintain consistent behavior across arity levels.
Where are predicate assertion macros defined in the GoogleTest source code?
The macros are defined in googletest/include/gtest/gtest_pred_impl.h. The public face of these macros is exposed through googletest/include/gtest/gtest.h, which is the header you include in test files. The AssertionResult type used by custom formatters is declared in googletest/include/gtest/gtest-assertion-result.h.
How do I include custom values in my predicate assertion failure messages?
Write a predicate-format function that takes const char* expression parameters followed by const T& value parameters, then return ::testing::AssertionFailure() << "your message" with the values inserted into the stream. Pass this function to EXPECT_PRED_FORMATn (where n matches your argument count) rather than using the plain EXPECT_PREDn macro.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →