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


i using gtest , gmock in applications , couldn't able understand purpose of setup() , teardown() functions in gtest. per understanding setup() function called before each test_f execution , teardown() called @ end. can use ::testing::test class constructor , destructor same purpose right? these function used?

you can use these functions (re-)establish state of resources shared among of test cases. in case when exceptions involved in test cases.

from documentation it's said:

you may still want use setup()/teardown() in following rare cases:

  • if tear-down operation throw exception, must use teardown() opposed destructor, throwing in destructor leads undefined behavior , kill program right away. note many standard libraries (like stl) may throw when exceptions enabled in compiler. therefore should prefer teardown() if want write portable tests work or without exceptions.
  • the assertion macros throw exception when flag --gtest_throw_on_failure specified. therefore, shouldn't use google test assertions in destructor if plan run tests flag.
  • in constructor or destructor, cannot make virtual function call on object. (you can call method declared virtual, statically bound.) therefore, if need call method overriden in derived class, have use setup()/teardown().

Comments