Googletest FAQ
Googletest FAQ
Googletest FAQ
Why should test suite names and test names not contain
underscore?
Underscore ( _ ) is special, as C++ reserves the following to be used by the compiler and the standard
library:
1. any identifier that starts with an _ followed by an upper-case letter, and
2. any identifier that contains two consecutive underscores (i.e. __ ) anywhere in its name.
User code is prohibited from using such identifiers.
Now let's look at what this means for TEST and TEST_F .
Currently TEST(TestSuiteName, TestName) generates a class named
TestSuiteName_TestName_Test . What happens if TestSuiteName or TestName contains _ ?
Now, the two TEST s will both generate the same class ( Time_Flies_Like_An_Arrow_Test ). That's
not good.
So for simplicity, we just ask the users to avoid _ in TestSuiteName and TestName . The rule is
more constraining than necessary, but it's simple and easy to remember. It also gives googletest some
wiggle room in case its implementation needs to change in the future.
If you violate the rule, there may not be immediate consequences, but your test may (just may) break
with a new compiler (or a new version of the compiler you are using) or with a new version of
googletest. Therefore it's best to follow the rule.
https://fuchsia.googlesource.com/third_party/googletest/+/HEAD/googletest/docs/faq.md#:~:text=If the tear-down operation,kill your program right away. 1/14
13/11/2024, 10:28 Googletest FAQ
differences, you can write factory function wrappers and pass these function pointers to the tests
as their parameters.
When a typed test fails, the default output includes the name of the type, which can help you
quickly identify which implementation is wrong. Value-parameterized tests only show the number
of the failed iteration by default. You will need to define a function that returns the iteration name
and pass it as the third parameter to INSTANTIATE_TEST_SUITE_P to have more useful output.
When using typed tests, you need to make sure you are testing against the interface type, not the
concrete types (in other words, you want to make sure implicit_cast<MyInterface*>
(my_concrete_impl) works, not just that my_concrete_impl works). It's less likely to make
mistakes in this area when using value-parameterized tests.
I hope I didn‘t confuse you more. :-) If you don’t mind, I'd suggest you to give both approaches a try.
Practice is a much better way to grasp the subtle differences between the two tools. Once you have
some concrete experience, you can much more easily decide which one to use the next time.
ProtocolMessageEquals and ProtocolMessageEquiv were redefined recently and are now less
tolerant of invalid protocol buffer definitions. In particular, if you have a foo.proto that doesn't fully
qualify the type of a protocol message it references (e.g. message<Bar> where it should be
message<blah.Bar> ), you will now get run-time errors like:
If you see this, your .proto file is broken and needs to be fixed by making the types fully qualified. The
new definition of ProtocolMessageEquals and ProtocolMessageEquiv just happen to reveal
your bug.
My death test modifies some state, but the change seems lost after
the death test finishes. Why?
Death tests ( EXPECT_DEATH , etc) are executed in a sub-process s.t. the expected crash won't kill the
test program (i.e. the parent process). As a result, any in-memory side effects they incur are observable
in their respective sub-processes, but not in the parent process. You can think of them as running in a
parallel universe, more or less.
In particular, if you use mocking and the death test statement invokes some mock methods, the parent
process will think the calls have never occurred. Therefore, you may want to move your EXPECT_CALL
statements inside the EXPECT_DEATH macro.
// foo.h
class Foo {
...
static const int kBar = 100;
};
Otherwise your code is invalid C++, and may break in unexpected ways. In particular, using it in
googletest comparison assertions ( EXPECT_EQ , etc) will generate an “undefined reference” linker error.
The fact that “it used to work” doesn‘t mean it’s valid. It just means that you were lucky. :-)
Yes.
Each test fixture has a corresponding and same named test suite. This means only one test suite can
use a particular fixture. Sometimes, however, multiple test cases may want to use the same or slightly
different fixtures. For example, you may want to make sure that all of a GUI library‘s test suites don’t
leak important system resources like fonts and brushes.
In googletest, you share a fixture among test suites by putting the shared logic in a base test fixture,
then deriving from that base a separate fixture for each test suite that wants to use this common logic.
You then use TEST_F() to write tests using each derived fixture.
Typically, your code looks like this:
If necessary, you can continue to derive test fixtures from a derived fixture. googletest has no limit on
how deep the hierarchy can be.
For a complete example using derived test fixtures, see sample5_unittest.cc.
You‘re probably using an ASSERT_*() in a function that doesn’t return void . ASSERT_*() can only
be used in void functions, due to exceptions being disabled by our build system. Please see more
details here.
If you go with thread-safe death tests, remember that they rerun the test program from the beginning
in the child process. Therefore make sure your program can run side-by-side with itself and is
deterministic.
In the end, this boils down to good concurrent programming. You have to make sure that there is no
race conditions or dead locks in your program. No silver bullet - sorry!
When you need to write per-test set-up and tear-down logic, you have the choice between using the test
fixture constructor/destructor or SetUp()/TearDown() . The former is usually preferred, as it has the
following benefits:
By initializing a member variable in the constructor, we have the option to make it const , which
helps prevent accidental changes to its value and makes the tests more obviously correct.
In case we need to subclass the test fixture class, the subclass' constructor is guaranteed to call
the base class' constructor first, and the subclass' destructor is guaranteed to call the base class'
destructor afterward. With SetUp()/TearDown() , a subclass may make the mistake of
forgetting to call the base class' SetUp()/TearDown() or call them at the wrong time.
You may still want to use SetUp()/TearDown() in the following cases:
C++ does not allow virtual function calls in constructors and destructors. You can call a method
declared as virtual, but it will not use dynamic dispatch, it will use the definition from the class the
constructor of which is currently executing. This is because calling a virtual method before the
derived class constructor has a chance to run is very dangerous - the virtual method might
operate on uninitialized data. Therefore, if you need to call a method that will be overridden in a
derived class, you have to use SetUp()/TearDown() .
In the body of a constructor (or destructor), it‘s not possible to use the ASSERT_xx macros.
Therefore, if the set-up operation could cause a fatal test failure that should prevent the test from
running, it’s necessary to use abort and abort the whole test executable, or to use SetUp()
instead of a constructor.
If the tear-down operation could throw an exception, you must use TearDown() as opposed to
the destructor, as throwing in a destructor leads to undefined behavior and usually will kill your
program right away. Note that many standard libraries (like STL) may throw when exceptions are
enabled in the compiler. Therefore you should prefer TearDown() if you want to write portable
tests that work with or without exceptions.
The googletest team is considering making the assertion macros throw on platforms where
exceptions are enabled (e.g. Windows, Mac OS, and Linux client-side), which will eliminate the
need for the user to propagate failures from a subroutine to its caller. Therefore, you shouldn't
use googletest assertions in a destructor if your code could run on such a platform.
If you see this error, you might want to switch to (ASSERT|EXPECT)_PRED_FORMAT* , which will also
give you a better failure message. If, however, that is not an option, you can resolve the problem by
explicitly telling the compiler which version to pick.
For example, suppose you have
bool IsPositive(int n) {
return n > 0;
}
bool IsPositive(double x) {
return x > 0;
}
EXPECT_PRED1(IsPositive, 5);
(The stuff inside the angled brackets for the static_cast operator is the type of the function pointer
for the int -version of IsPositive() .)
As another example, when you have a template function
https://fuchsia.googlesource.com/third_party/googletest/+/HEAD/googletest/docs/faq.md#:~:text=If the tear-down operation,kill your program right away. 7/14
13/11/2024, 10:28 Googletest FAQ
ASSERT_PRED1(IsNegative<int>, -5);
Things are more interesting if your template has more than one parameters. The following won't
compile:
as the C++ pre-processor thinks you are giving ASSERT_PRED2 4 arguments, which is one more than
expected. The workaround is to wrap the predicate function in parentheses:
return RUN_ALL_TESTS();
they write
RUN_ALL_TESTS();
This is wrong and dangerous. The testing services needs to see the return value of
RUN_ALL_TESTS() in order to determine if a test has passed. If your main() function ignores it, your
test will be considered successful even if it has a googletest assertion failure. Very bad.
We have decided to fix this (thanks to Michael Chastain for the idea). Now, your code will no longer be
able to ignore RUN_ALL_TESTS() when compiled with gcc . If you do so, you'll get a compiler error.
If you see the compiler complaining about you ignoring the return value of RUN_ALL_TESTS() , the fix
is simple: just make sure its value is used as the return value of main() .
But how could we introduce a change that breaks existing tests? Well, in this case, the code was already
broken in the first place, so we didn't break it. :-)
Due to a peculiarity of C++, in order to support the syntax for streaming messages to an ASSERT_* ,
e.g.
we had to give up using ASSERT* and FAIL* (but not EXPECT* and ADD_FAILURE* ) in constructors
and destructors. The workaround is to move the content of your constructor/destructor to a private
void member function, or switch to EXPECT_*() if that works. This section in the user's guide explains
it.
I have several test suites which share the same test fixture logic, do I
have to define a new test fixture class for each of them? This seems
pretty tedious.
You don't have to. Instead of
The new NPTL thread library doesn‘t suffer from this problem, as it doesn’t create a manager thread.
However, if you don‘t control which machine your test runs on, you shouldn’t depend on this.
Since FooTest.AbcDeathTest needs to run before BarTest.Xyz , and we don't interleave tests
from different test suites, we need to run all tests in the FooTest case before running any test in the
BarTest case. This contradicts with the requirement to run BarTest.DefDeathTest before
FooTest.Uvw .
The compiler complains about “no match for ‘operator<<’” when I use
an assertion. What gives?
If you use a user-defined type FooType in an assertion, you must make sure there is an
std::ostream& operator<<(std::ostream&, const FooType&) function defined such that we
can print a value of FooType .
In addition, if FooType is declared in a name space, the << operator also needs to be defined in the
same name space. See https://abseil.io/tips/49 for details.
To include disabled tests in test execution, just invoke the test program with the --
gtest_also_run_disabled_tests flag.
namespace foo {
TEST(CoolTest, DoSomething) {
SUCCEED();
}
} // namespace foo
namespace bar {
TEST(CoolTest, DoSomething) {
SUCCEED();
}
} // namespace bar
However, the following code is not allowed and will produce a runtime error from googletest because
the test methods are using different test fixture classes with the same test suite name.
namespace foo {
class CoolTest : public ::testing::Test {}; // Fixture foo::CoolTest
TEST_F(CoolTest, DoSomething) {
SUCCEED();
}
} // namespace foo
namespace bar {
class CoolTest : public ::testing::Test {}; // Fixture: bar::CoolTest
TEST_F(CoolTest, DoSomething) {
SUCCEED();
}
} // namespace bar