TearDown() 和 Setup() 函数有什么好处?

What are the benefits with TearDown() and Setup() function?

我在我的应用程序中使用 gtestgmock,但我无法理解 gtestSetup()Teardown() 函数的用途]. 根据我的理解,Setup() 函数将在每次 TEST_F 执行之前被调用,而 Teardown() 将在最后被调用。我们可以使用 ::testing::Test class constructordestructor 来达到同样的目的吧?这些函数具体用在什么地方?

您可以使用这些函数来(重新)建立在所有测试用例之间共享的特定资源状态。尤其是在你的测试用例中涉及异常的情况下。

他们的 documentation 说:

You may still want to use SetUp()/TearDown() in the following rare cases:

  • 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 assertion macros throw an exception when flag --gtest_throw_on_failure is specified. Therefore, you shouldn't use Google Test assertions in a destructor if you plan to run your tests with this flag.
  • In a constructor or destructor, you cannot make a virtual function call on this object. (You can call a method declared as virtual, but it will be statically bound.) Therefore, if you need to call a method that will be overriden in a derived class, you have to use SetUp()/TearDown().