ImperialCollegeLondon / ImperialCollegeLondon/unit_testing_Cpp
Fixtures: prefer ctor/dtor over `SetUp`/`TearDown`
- Dominant language
- HTML
- Stars
- 2
- Forks
- 3
- PR merge metrics
- No merged PRs in 30d
Description
In the test fixture code and examples: change code and/or reference gTest FAQ:
It seems that (from the gtest faq: http://google.github.io/googletest/faq.html#CtorVsSetUp) the constructor/destructor should in fact be preferred ofer the SetUp/`TearDown` virtual functions, except in a few arguably avoidable situations:
> 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.
Contributor guide
Research direction
Locate the test fixture code and examples mentioned in the issue, then compare their setup and teardown patterns with the linked gTest FAQ guidance. Update the applicable fixtures or reference material so constructors and destructors are preferred where the listed exceptions do not apply, and verify the examples remain consistent.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp
- Domain
- testing
- Issue type
- Refactor
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100