3 This page lists the assertion macros provided by GoogleTest for verifying code
4 behavior. To use them, include the header `gtest/gtest.h`.
6 The majority of the macros listed below come as a pair with an `EXPECT_` variant
7 and an `ASSERT_` variant. Upon failure, `EXPECT_` macros generate nonfatal
8 failures and allow the current function to continue running, while `ASSERT_`
9 macros generate fatal failures and abort the current function.
11 All assertion macros support streaming a custom failure message into them with
12 the `<<` operator, for example:
15 EXPECT_TRUE(my_condition) << "My condition is not true";
18 Anything that can be streamed to an `ostream` can be streamed to an assertion
19 macro—in particular, C strings and string objects. If a wide string (`wchar_t*`,
20 `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is streamed to an
21 assertion, it will be translated to UTF-8 when printed.
23 ## Explicit Success and Failure {#success-failure}
25 The assertions in this section generate a success or failure directly instead of
26 testing a value or expression. These are useful when control flow, rather than a
27 Boolean expression, determines the test's success or failure, as shown by the
35 ... some other checks ...
37 FAIL() << "We shouldn't get here.";
41 ### SUCCEED {#SUCCEED}
45 Generates a success. This *does not* make the overall test succeed. A test is
46 considered successful only if none of its assertions fail during its execution.
48 The `SUCCEED` assertion is purely documentary and currently doesn't generate any
49 user-visible output. However, we may add `SUCCEED` messages to GoogleTest output
56 Generates a fatal failure, which returns from the current function.
58 Can only be used in functions that return `void`. See
59 [Assertion Placement](../advanced.md#assertion-placement) for more information.
61 ### ADD_FAILURE {#ADD_FAILURE}
65 Generates a nonfatal failure, which allows the current function to continue
68 ### ADD_FAILURE_AT {#ADD_FAILURE_AT}
70 `ADD_FAILURE_AT(`*`file_path`*`,`*`line_number`*`)`
72 Generates a nonfatal failure at the file and line number specified.
74 ## Generalized Assertion {#generalized}
76 The following assertion allows [matchers](matchers.md) to be used to verify
79 ### EXPECT_THAT {#EXPECT_THAT}
81 `EXPECT_THAT(`*`value`*`,`*`matcher`*`)` \
82 `ASSERT_THAT(`*`value`*`,`*`matcher`*`)`
84 Verifies that *`value`* matches the [matcher](matchers.md) *`matcher`*.
86 For example, the following code verifies that the string `value1` starts with
87 `"Hello"`, `value2` matches a regular expression, and `value3` is between 5 and
91 #include "gmock/gmock.h"
93 using ::testing::AllOf;
96 using ::testing::MatchesRegex;
97 using ::testing::StartsWith;
100 EXPECT_THAT(value1, StartsWith("Hello"));
101 EXPECT_THAT(value2, MatchesRegex("Line \\d+"));
102 ASSERT_THAT(value3, AllOf(Gt(5), Lt(10)));
105 Matchers enable assertions of this form to read like English and generate
106 informative failure messages. For example, if the above assertion on `value1`
107 fails, the resulting message will be similar to the following:
112 Expected: starts with "Hello"
115 GoogleTest provides a built-in library of matchers—see the
116 [Matchers Reference](matchers.md). It is also possible to write your own
117 matchers—see [Writing New Matchers Quickly](../gmock_cook_book.md#NewMatchers).
118 The use of matchers makes `EXPECT_THAT` a powerful, extensible assertion.
120 *The idea for this assertion was borrowed from Joe Walnes' Hamcrest project,
121 which adds `assertThat()` to JUnit.*
123 ## Boolean Conditions {#boolean}
125 The following assertions test Boolean conditions.
127 ### EXPECT_TRUE {#EXPECT_TRUE}
129 `EXPECT_TRUE(`*`condition`*`)` \
130 `ASSERT_TRUE(`*`condition`*`)`
132 Verifies that *`condition`* is true.
134 ### EXPECT_FALSE {#EXPECT_FALSE}
136 `EXPECT_FALSE(`*`condition`*`)` \
137 `ASSERT_FALSE(`*`condition`*`)`
139 Verifies that *`condition`* is false.
141 ## Binary Comparison {#binary-comparison}
143 The following assertions compare two values. The value arguments must be
144 comparable by the assertion's comparison operator, otherwise a compiler error
147 If an argument supports the `<<` operator, it will be called to print the
148 argument when the assertion fails. Otherwise, GoogleTest will attempt to print
149 them in the best way it can—see
150 [Teaching GoogleTest How to Print Your Values](../advanced.md#teaching-googletest-how-to-print-your-values).
152 Arguments are always evaluated exactly once, so it's OK for the arguments to
153 have side effects. However, the argument evaluation order is undefined and
154 programs should not depend on any particular argument evaluation order.
156 These assertions work with both narrow and wide string objects (`string` and
159 See also the [Floating-Point Comparison](#floating-point) assertions to compare
160 floating-point numbers and avoid problems caused by rounding.
162 ### EXPECT_EQ {#EXPECT_EQ}
164 `EXPECT_EQ(`*`val1`*`,`*`val2`*`)` \
165 `ASSERT_EQ(`*`val1`*`,`*`val2`*`)`
167 Verifies that *`val1`*`==`*`val2`*.
169 Does pointer equality on pointers. If used on two C strings, it tests if they
170 are in the same memory location, not if they have the same value. Use
171 [`EXPECT_STREQ`](#EXPECT_STREQ) to compare C strings (e.g. `const char*`) by
174 When comparing a pointer to `NULL`, use `EXPECT_EQ(`*`ptr`*`, nullptr)` instead
175 of `EXPECT_EQ(`*`ptr`*`, NULL)`.
177 ### EXPECT_NE {#EXPECT_NE}
179 `EXPECT_NE(`*`val1`*`,`*`val2`*`)` \
180 `ASSERT_NE(`*`val1`*`,`*`val2`*`)`
182 Verifies that *`val1`*`!=`*`val2`*.
184 Does pointer equality on pointers. If used on two C strings, it tests if they
185 are in different memory locations, not if they have different values. Use
186 [`EXPECT_STRNE`](#EXPECT_STRNE) to compare C strings (e.g. `const char*`) by
189 When comparing a pointer to `NULL`, use `EXPECT_NE(`*`ptr`*`, nullptr)` instead
190 of `EXPECT_NE(`*`ptr`*`, NULL)`.
192 ### EXPECT_LT {#EXPECT_LT}
194 `EXPECT_LT(`*`val1`*`,`*`val2`*`)` \
195 `ASSERT_LT(`*`val1`*`,`*`val2`*`)`
197 Verifies that *`val1`*`<`*`val2`*.
199 ### EXPECT_LE {#EXPECT_LE}
201 `EXPECT_LE(`*`val1`*`,`*`val2`*`)` \
202 `ASSERT_LE(`*`val1`*`,`*`val2`*`)`
204 Verifies that *`val1`*`<=`*`val2`*.
206 ### EXPECT_GT {#EXPECT_GT}
208 `EXPECT_GT(`*`val1`*`,`*`val2`*`)` \
209 `ASSERT_GT(`*`val1`*`,`*`val2`*`)`
211 Verifies that *`val1`*`>`*`val2`*.
213 ### EXPECT_GE {#EXPECT_GE}
215 `EXPECT_GE(`*`val1`*`,`*`val2`*`)` \
216 `ASSERT_GE(`*`val1`*`,`*`val2`*`)`
218 Verifies that *`val1`*`>=`*`val2`*.
220 ## String Comparison {#c-strings}
222 The following assertions compare two **C strings**. To compare two `string`
223 objects, use [`EXPECT_EQ`](#EXPECT_EQ) or [`EXPECT_NE`](#EXPECT_NE) instead.
225 These assertions also accept wide C strings (`wchar_t*`). If a comparison of two
226 wide strings fails, their values will be printed as UTF-8 narrow strings.
228 To compare a C string with `NULL`, use `EXPECT_EQ(`*`c_string`*`, nullptr)` or
229 `EXPECT_NE(`*`c_string`*`, nullptr)`.
231 ### EXPECT_STREQ {#EXPECT_STREQ}
233 `EXPECT_STREQ(`*`str1`*`,`*`str2`*`)` \
234 `ASSERT_STREQ(`*`str1`*`,`*`str2`*`)`
236 Verifies that the two C strings *`str1`* and *`str2`* have the same contents.
238 ### EXPECT_STRNE {#EXPECT_STRNE}
240 `EXPECT_STRNE(`*`str1`*`,`*`str2`*`)` \
241 `ASSERT_STRNE(`*`str1`*`,`*`str2`*`)`
243 Verifies that the two C strings *`str1`* and *`str2`* have different contents.
245 ### EXPECT_STRCASEEQ {#EXPECT_STRCASEEQ}
247 `EXPECT_STRCASEEQ(`*`str1`*`,`*`str2`*`)` \
248 `ASSERT_STRCASEEQ(`*`str1`*`,`*`str2`*`)`
250 Verifies that the two C strings *`str1`* and *`str2`* have the same contents,
253 ### EXPECT_STRCASENE {#EXPECT_STRCASENE}
255 `EXPECT_STRCASENE(`*`str1`*`,`*`str2`*`)` \
256 `ASSERT_STRCASENE(`*`str1`*`,`*`str2`*`)`
258 Verifies that the two C strings *`str1`* and *`str2`* have different contents,
261 ## Floating-Point Comparison {#floating-point}
263 The following assertions compare two floating-point values.
265 Due to rounding errors, it is very unlikely that two floating-point values will
266 match exactly, so `EXPECT_EQ` is not suitable. In general, for floating-point
267 comparison to make sense, the user needs to carefully choose the error bound.
269 GoogleTest also provides assertions that use a default error bound based on
270 Units in the Last Place (ULPs). To learn more about ULPs, see the article
271 [Comparing Floating Point Numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
273 ### EXPECT_FLOAT_EQ {#EXPECT_FLOAT_EQ}
275 `EXPECT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)` \
276 `ASSERT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)`
278 Verifies that the two `float` values *`val1`* and *`val2`* are approximately
279 equal, to within 4 ULPs from each other.
281 ### EXPECT_DOUBLE_EQ {#EXPECT_DOUBLE_EQ}
283 `EXPECT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)` \
284 `ASSERT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)`
286 Verifies that the two `double` values *`val1`* and *`val2`* are approximately
287 equal, to within 4 ULPs from each other.
289 ### EXPECT_NEAR {#EXPECT_NEAR}
291 `EXPECT_NEAR(`*`val1`*`,`*`val2`*`,`*`abs_error`*`)` \
292 `ASSERT_NEAR(`*`val1`*`,`*`val2`*`,`*`abs_error`*`)`
294 Verifies that the difference between *`val1`* and *`val2`* does not exceed the
295 absolute error bound *`abs_error`*.
297 ## Exception Assertions {#exceptions}
299 The following assertions verify that a piece of code throws, or does not throw,
300 an exception. Usage requires exceptions to be enabled in the build environment.
302 Note that the piece of code under test can be a compound statement, for example:
311 ### EXPECT_THROW {#EXPECT_THROW}
313 `EXPECT_THROW(`*`statement`*`,`*`exception_type`*`)` \
314 `ASSERT_THROW(`*`statement`*`,`*`exception_type`*`)`
316 Verifies that *`statement`* throws an exception of type *`exception_type`*.
318 ### EXPECT_ANY_THROW {#EXPECT_ANY_THROW}
320 `EXPECT_ANY_THROW(`*`statement`*`)` \
321 `ASSERT_ANY_THROW(`*`statement`*`)`
323 Verifies that *`statement`* throws an exception of any type.
325 ### EXPECT_NO_THROW {#EXPECT_NO_THROW}
327 `EXPECT_NO_THROW(`*`statement`*`)` \
328 `ASSERT_NO_THROW(`*`statement`*`)`
330 Verifies that *`statement`* does not throw any exception.
332 ## Predicate Assertions {#predicates}
334 The following assertions enable more complex predicates to be verified while
335 printing a more clear failure message than if `EXPECT_TRUE` were used alone.
337 ### EXPECT_PRED* {#EXPECT_PRED}
339 `EXPECT_PRED1(`*`pred`*`,`*`val1`*`)` \
340 `EXPECT_PRED2(`*`pred`*`,`*`val1`*`,`*`val2`*`)` \
341 `EXPECT_PRED3(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \
342 `EXPECT_PRED4(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` \
343 `EXPECT_PRED5(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)`
345 `ASSERT_PRED1(`*`pred`*`,`*`val1`*`)` \
346 `ASSERT_PRED2(`*`pred`*`,`*`val1`*`,`*`val2`*`)` \
347 `ASSERT_PRED3(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \
348 `ASSERT_PRED4(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` \
349 `ASSERT_PRED5(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)`
351 Verifies that the predicate *`pred`* returns `true` when passed the given values
354 The parameter *`pred`* is a function or functor that accepts as many arguments
355 as the corresponding macro accepts values. If *`pred`* returns `true` for the
356 given arguments, the assertion succeeds, otherwise the assertion fails.
358 When the assertion fails, it prints the value of each argument. Arguments are
359 always evaluated exactly once.
361 As an example, see the following code:
364 // Returns true if m and n have no common divisors except 1.
365 bool MutuallyPrime(int m, int n) { ... }
371 EXPECT_PRED2(MutuallyPrime, a, b); // Succeeds
372 EXPECT_PRED2(MutuallyPrime, b, c); // Fails
375 In the above example, the first assertion succeeds, and the second fails with
376 the following message:
379 MutuallyPrime(b, c) is false, where
384 Note that if the given predicate is an overloaded function or a function
385 template, the assertion macro might not be able to determine which version to
386 use, and it might be necessary to explicitly specify the type of the function.
387 For example, for a Boolean function `IsPositive()` overloaded to take either a
388 single `int` or `double` argument, it would be necessary to write one of the
392 EXPECT_PRED1(static_cast<bool (*)(int)>(IsPositive), 5);
393 EXPECT_PRED1(static_cast<bool (*)(double)>(IsPositive), 3.14);
396 Writing simply `EXPECT_PRED1(IsPositive, 5);` would result in a compiler error.
397 Similarly, to use a template function, specify the template arguments:
400 template <typename T>
401 bool IsNegative(T x) {
405 EXPECT_PRED1(IsNegative<int>, -5); // Must specify type for IsNegative
408 If a template has multiple parameters, wrap the predicate in parentheses so the
409 macro arguments are parsed correctly:
412 ASSERT_PRED2((MyPredicate<int, int>), 5, 0);
415 ### EXPECT_PRED_FORMAT* {#EXPECT_PRED_FORMAT}
417 `EXPECT_PRED_FORMAT1(`*`pred_formatter`*`,`*`val1`*`)` \
418 `EXPECT_PRED_FORMAT2(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`)` \
419 `EXPECT_PRED_FORMAT3(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \
420 `EXPECT_PRED_FORMAT4(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)`
422 `EXPECT_PRED_FORMAT5(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)`
424 `ASSERT_PRED_FORMAT1(`*`pred_formatter`*`,`*`val1`*`)` \
425 `ASSERT_PRED_FORMAT2(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`)` \
426 `ASSERT_PRED_FORMAT3(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \
427 `ASSERT_PRED_FORMAT4(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)`
429 `ASSERT_PRED_FORMAT5(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)`
431 Verifies that the predicate *`pred_formatter`* succeeds when passed the given
434 The parameter *`pred_formatter`* is a *predicate-formatter*, which is a function
435 or functor with the signature:
438 testing::AssertionResult PredicateFormatter(const char* expr1,
448 where *`val1`*, *`val2`*, ..., *`valn`* are the values of the predicate
449 arguments, and *`expr1`*, *`expr2`*, ..., *`exprn`* are the corresponding
450 expressions as they appear in the source code. The types `T1`, `T2`, ..., `Tn`
451 can be either value types or reference types; if an argument has type `T`, it
452 can be declared as either `T` or `const T&`, whichever is appropriate. For more
453 about the return type `testing::AssertionResult`, see
454 [Using a Function That Returns an AssertionResult](../advanced.md#using-a-function-that-returns-an-assertionresult).
456 As an example, see the following code:
459 // Returns the smallest prime common divisor of m and n,
460 // or 1 when m and n are mutually prime.
461 int SmallestPrimeCommonDivisor(int m, int n) { ... }
463 // Returns true if m and n have no common divisors except 1.
464 bool MutuallyPrime(int m, int n) { ... }
466 // A predicate-formatter for asserting that two integers are mutually prime.
467 testing::AssertionResult AssertMutuallyPrime(const char* m_expr,
471 if (MutuallyPrime(m, n)) return testing::AssertionSuccess();
473 return testing::AssertionFailure() << m_expr << " and " << n_expr
474 << " (" << m << " and " << n << ") are not mutually prime, "
475 << "as they have a common divisor " << SmallestPrimeCommonDivisor(m, n);
483 EXPECT_PRED_FORMAT2(AssertMutuallyPrime, a, b); // Succeeds
484 EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); // Fails
487 In the above example, the final assertion fails and the predicate-formatter
488 produces the following failure message:
491 b and c (4 and 10) are not mutually prime, as they have a common divisor 2
494 ## Windows HRESULT Assertions {#HRESULT}
496 The following assertions test for `HRESULT` success or failure. For example:
499 CComPtr<IShellDispatch2> shell;
500 ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application"));
502 ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty));
505 The generated output contains the human-readable error message associated with
506 the returned `HRESULT` code.
508 ### EXPECT_HRESULT_SUCCEEDED {#EXPECT_HRESULT_SUCCEEDED}
510 `EXPECT_HRESULT_SUCCEEDED(`*`expression`*`)` \
511 `ASSERT_HRESULT_SUCCEEDED(`*`expression`*`)`
513 Verifies that *`expression`* is a success `HRESULT`.
515 ### EXPECT_HRESULT_FAILED {#EXPECT_HRESULT_FAILED}
517 `EXPECT_HRESULT_FAILED(`*`expression`*`)` \
518 `EXPECT_HRESULT_FAILED(`*`expression`*`)`
520 Verifies that *`expression`* is a failure `HRESULT`.
522 ## Death Assertions {#death}
524 The following assertions verify that a piece of code causes the process to
525 terminate. For context, see [Death Tests](../advanced.md#death-tests).
527 These assertions spawn a new process and execute the code under test in that
528 process. How that happens depends on the platform and the variable
529 `::testing::GTEST_FLAG(death_test_style)`, which is initialized from the
530 command-line flag `--gtest_death_test_style`.
532 * On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the
534 * If the variable's value is `"fast"`, the death test statement is
535 immediately executed.
536 * If the variable's value is `"threadsafe"`, the child process re-executes
537 the unit test binary just as it was originally invoked, but with some
538 extra flags to cause just the single death test under consideration to
540 * On Windows, the child is spawned using the `CreateProcess()` API, and
541 re-executes the binary to cause just the single death test under
542 consideration to be run - much like the `"threadsafe"` mode on POSIX.
544 Other values for the variable are illegal and will cause the death test to fail.
545 Currently, the flag's default value is
548 If the death test statement runs to completion without dying, the child process
549 will nonetheless terminate, and the assertion fails.
551 Note that the piece of code under test can be a compound statement, for example:
557 }, "Error on line .* of DoSomething()");
560 ### EXPECT_DEATH {#EXPECT_DEATH}
562 `EXPECT_DEATH(`*`statement`*`,`*`matcher`*`)` \
563 `ASSERT_DEATH(`*`statement`*`,`*`matcher`*`)`
565 Verifies that *`statement`* causes the process to terminate with a nonzero exit
566 status and produces `stderr` output that matches *`matcher`*.
568 The parameter *`matcher`* is either a [matcher](matchers.md) for a `const
569 std::string&`, or a regular expression (see
570 [Regular Expression Syntax](../advanced.md#regular-expression-syntax))—a bare
571 string *`s`* (with no matcher) is treated as
572 [`ContainsRegex(s)`](matchers.md#string-matchers), **not**
573 [`Eq(s)`](matchers.md#generic-comparison).
575 For example, the following code verifies that calling `DoSomething(42)` causes
576 the process to die with an error message that contains the text `My error`:
579 EXPECT_DEATH(DoSomething(42), "My error");
582 ### EXPECT_DEATH_IF_SUPPORTED {#EXPECT_DEATH_IF_SUPPORTED}
584 `EXPECT_DEATH_IF_SUPPORTED(`*`statement`*`,`*`matcher`*`)` \
585 `ASSERT_DEATH_IF_SUPPORTED(`*`statement`*`,`*`matcher`*`)`
587 If death tests are supported, behaves the same as
588 [`EXPECT_DEATH`](#EXPECT_DEATH). Otherwise, verifies nothing.
590 ### EXPECT_DEBUG_DEATH {#EXPECT_DEBUG_DEATH}
592 `EXPECT_DEBUG_DEATH(`*`statement`*`,`*`matcher`*`)` \
593 `ASSERT_DEBUG_DEATH(`*`statement`*`,`*`matcher`*`)`
595 In debug mode, behaves the same as [`EXPECT_DEATH`](#EXPECT_DEATH). When not in
596 debug mode (i.e. `NDEBUG` is defined), just executes *`statement`*.
598 ### EXPECT_EXIT {#EXPECT_EXIT}
600 `EXPECT_EXIT(`*`statement`*`,`*`predicate`*`,`*`matcher`*`)` \
601 `ASSERT_EXIT(`*`statement`*`,`*`predicate`*`,`*`matcher`*`)`
603 Verifies that *`statement`* causes the process to terminate with an exit status
604 that satisfies *`predicate`*, and produces `stderr` output that matches
607 The parameter *`predicate`* is a function or functor that accepts an `int` exit
608 status and returns a `bool`. GoogleTest provides two predicates to handle common
612 // Returns true if the program exited normally with the given exit status code.
613 ::testing::ExitedWithCode(exit_code);
615 // Returns true if the program was killed by the given signal.
616 // Not available on Windows.
617 ::testing::KilledBySignal(signal_number);
620 The parameter *`matcher`* is either a [matcher](matchers.md) for a `const
621 std::string&`, or a regular expression (see
622 [Regular Expression Syntax](../advanced.md#regular-expression-syntax))—a bare
623 string *`s`* (with no matcher) is treated as
624 [`ContainsRegex(s)`](matchers.md#string-matchers), **not**
625 [`Eq(s)`](matchers.md#generic-comparison).
627 For example, the following code verifies that calling `NormalExit()` causes the
628 process to print a message containing the text `Success` to `stderr` and exit
629 with exit status code 0:
632 EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success");