How to Create Custom AssertionResult Objects in GoogleTest
Use the testing::AssertionSuccess() and testing::AssertionFailure() factory functions to construct testing::AssertionResult objects, streaming custom diagnostic messages with the << operator before returning them from predicate functions used with EXPECT_TRUE or ASSERT_TRUE.
The testing::AssertionResult class in the google/googletest framework provides a lightweight mechanism for returning rich boolean results with attached failure messages. Unlike plain bool returns, custom AssertionResult objects let you defer message construction until failure occurs and integrate seamlessly with GoogleTest's reporting macros. This pattern is implemented in googletest/include/gtest/gtest-assertion-result.h and documented in the advanced guide for writing expressive, self-documenting test predicates.
Understanding the AssertionResult Class Architecture
According to the source code in googletest/include/gtest/gtest-assertion-result.h, the AssertionResult class stores two private members: a bool success_ indicating the predicate outcome, and a Message message_ containing the diagnostic string. The class provides an operator bool() const conversion operator that macros like EXPECT_TRUE use to evaluate the boolean value, while an overloaded operator<< (lines 186-207) enables lazy concatenation of additional context without evaluating expensive expressions on success.
Factory Functions for Constructing Custom Results
GoogleTest exposes two factory functions in the same header file (lines 251-259) to create AssertionResult instances without accessing private constructors:
testing::AssertionSuccess()– Returns a result wheresuccess_istrueand the message stream is empty.testing::AssertionFailure()– Returns a result wheresuccess_isfalseand exposes a stream interface viaoperator<<for immediate message attachment.
These factories are documented in docs/reference/assertions.md under the Success/Failure section and represent the only supported construction mechanism for user code.
Implementing Custom Predicate Functions
To create a custom AssertionResult, write a free function or functor that returns testing::AssertionResult and invoke it through GoogleTest's boolean assertion macros. Follow this implementation pattern:
- Return
testing::AssertionSuccess()when the predicate condition is met. - Return
testing::AssertionFailure()followed by<<messages when the condition fails. - Stream contextual data using the
<<operator to build detailed diagnostic output. - Pass the function to
EXPECT_TRUE,EXPECT_FALSE,ASSERT_TRUE, orASSERT_FALSE.
Basic Predicate with Custom Failure Messages
The following predicate checks for even numbers and provides specific failure diagnostics:
// File: my_predicates.h
#include <gtest/gtest.h>
testing::AssertionResult IsEven(int n) {
if (n % 2 == 0) {
return testing::AssertionSuccess(); // Calls factory at gtest-assertion-result.h:251
} else {
return testing::AssertionFailure() << n << " is odd";
}
}
// File: my_test.cc
#include "my_predicates.h"
TEST(NumberTest, Evenness) {
EXPECT_TRUE(IsEven(4)); // Passes silently
EXPECT_TRUE(IsEven(5)); // Fails with: "Value of: IsEven(5) Actual: false (5 is odd)"
}
Providing Success Messages for EXPECT_FALSE
When using EXPECT_FALSE to verify that a condition does not hold, attaching a message to AssertionSuccess() provides valuable context when the test unexpectedly passes:
testing::AssertionResult IsPrime(int n) {
if (n < 2) {
return testing::AssertionFailure() << n << " is not prime (too small)";
}
for (int i = 2; i * i <= n; ++i) {
if (n % i == 0) {
return testing::AssertionFailure() << n << " is divisible by " << i;
}
}
return testing::AssertionSuccess() << n << " is prime";
}
TEST(PrimeTest, Validation) {
EXPECT_FALSE(IsPrime(4)); // Prints: "Actual: false (4 is divisible by 2)"
EXPECT_FALSE(IsPrime(7)); // Prints: "Actual: false (7 is prime)"
}
Stateful Functors for Complex Validation
For predicates requiring configuration or persistent state, implement a functor that stores parameters and defines operator() returning AssertionResult:
struct ContainsSubstring {
explicit ContainsSubstring(const std::string& sub) : sub_(sub) {}
testing::AssertionResult operator()(const std::string& s) const {
if (s.find(sub_) != std::string::npos) {
return testing::AssertionSuccess() << "'" << s << "' contains '" << sub_ << "'";
}
return testing::AssertionFailure() << "'" << s << "' does not contain '" << sub_ << "'";
}
std::string sub_;
};
TEST(StringTest, Contains) {
ContainsSubstring has_foo("foo");
EXPECT_TRUE(has_foo("foobar")); // Succeeds
EXPECT_TRUE(has_foo("barbaz")); // Fails with detailed message about missing substring
}
Integration with GoogleTest Macros
When a predicate returns an AssertionResult, the macros check the boolean conversion operator. If the conversion yields false, the macro prints the stored message_ content alongside the standard Value of: line. This design, documented in docs/advanced.md under Using a Function That Returns an AssertionResult, ensures that expensive message formatting only occurs when necessary, while maintaining compatibility with the streaming interface defined at lines 186-207 of gtest-assertion-result.h.
Summary
- The
testing::AssertionResultclass ingoogletest/include/gtest/gtest-assertion-result.hencapsulates a boolean state and optional message throughsuccess_andmessage_members. - Use
testing::AssertionSuccess()andtesting::AssertionFailure()(lines 251-259) to instantiate results without direct constructor access. - Stream custom diagnostics using
operator<<before returning from predicate functions to provide context-rich failure messages. - Invoke custom predicates through
EXPECT_TRUE,EXPECT_FALSE,ASSERT_TRUE, orASSERT_FALSE, which evaluate the boolean conversion operator. - The mechanism avoids double-evaluation of expressions and supports both free functions and stateful functors.
Frequently Asked Questions
Can I subclass AssertionResult to add custom behavior?
No, you should not subclass AssertionResult. Instead, write free functions or functors that return testing::AssertionResult objects constructed via the factory functions. The class is designed to be a lightweight value type passed by value, not a polymorphic base class, as implemented in googletest/include/gtest/gtest-assertion-result.h.
Why use AssertionResult instead of returning bool and printing manually?
Returning a custom AssertionResult allows the macro to control when messages are printed and avoids evaluating expensive formatting expressions when assertions pass. The AssertionFailure() factory captures the message stream in the message_ member, which macros display only when the boolean conversion operator returns false.
How do I create a custom AssertionResult for library code outside GoogleTest?
Include <gtest/gtest.h> (which pulls in gtest-assertion-result.h) and implement predicate functions in your own header files, such as my_predicates.h. The factory functions AssertionSuccess() and AssertionFailure() are part of the public API documented in docs/reference/assertions.md and require no modifications to the GoogleTest framework itself.
Do AssertionResult objects work with ASSERT variants like ASSERT_TRUE?
Yes, AssertionResult works identically with ASSERT_TRUE, ASSERT_FALSE, EXPECT_TRUE, and EXPECT_FALSE. The macros use the same implicit conversion to bool to evaluate the result, and failure messages are printed before the test case aborts (for ASSERT variants) or continues (for EXPECT variants).
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 →