Recommended pattern for GTEST_SKIP called from SetUp in a base class and dealing with that in derived classes #4879
Replies: 1 comment 2 replies
|
@greggman Great question! You've identified a real design issue. The core problem is that GTEST_SKIP() throws an exception internally, but derived SetUp() methods can still execute afterward if you don't explicitly return, creating a fragile pattern that requires defensive programming. Two recommended approaches:1. Encapsulate preconditions in the base classHave the base class handle all conditional setup and guarantee that if execution reaches derived SetUp(), preconditions already hold: class Base : public ::testing::Test { class Derived : public Base { 2. Use virtual hooks for optional resourcesProvide hooks that only run when preconditions are satisfied: class Base : public ::testing::Test { class Derived : public Base { Both patterns eliminate the need for every derived class to defensively check IsSkipped(), making the contract explicit: either the base guarantees preconditions or the test is skipped before derived logic runs. This is much safer than relying on manual vigilance throughout your test hierarchy. |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I work on a big project that has 1000s of googletests. I recently noticed the tests are full of a pattern like this
Note: In the actual code it's not
NoFileSystembut it's effectively the same idea. TheBase::SetUpcallsGTEST_SKIPand the derived classes are all written as those they won't get executed ifBase::SetUpfails.They can all be re-written, I guess, to do this
But it means every derived class has to follow this pattern as someday its base might call
GTEST_SKIP. Coding by vigilance seems likely to have missed cases.I'm curious if there is a recommended way to structure this situation so as not to require the vigilance. It seems like it would be a common issue.
All reactions