Because the standard I/O streams (cout, cin, cerr) remain available until
after static object destruction, if you want to verify that the destructor runs, you could just put a message out to cout from within the destructor and look for the message. I've made use of this feature as indicated in the above link. This is best done as a one-time test, rather than as an ongoing test under gtest. Realistically, the destructor running isn't something that is going to stop working as you further modify your code.
Dave Wallace
On Tuesday, July 31, 2012 4:22:23 PM UTC-7, Matthew Woehlke wrote:
Here's a puzzle... I am trying to write a test to verify that a destructor of a static object runs (it is a test for a singleton pattern implementation). Is there any way to do this?
I thought to write a death test and have the destructor cause an abnormal termination (e.g. assert(false)... note that is 'assert' i.e. '#include <cassert>', not a gtest assert), however it seems gtest does something when it finishes executing the EXPECT_DEATH statement that prevents static destructors from executing.
Can this approach be made to work? If not, is there some other approach I might use? (Offhand, the only other option I can think of is to build a shared library just for the test that contains a singleton accessor, dlopen() the library, grab the singleton to ensure construction, and then dlclose() it to cause the destructor to fire. However this would require non-portable code for interacting with the library.)