Search code examples
c++windowsboost-test

Suppress exit signal in Boost.Test


I would like to test a method in my program, which handles shutdown of the application. At the end this method calls exit(0);

As expected this shuts also my test application down.

Is there a possibility to catch the exit signal in this particular unit test, so the shutdown of the test application can be avoided?


Solution

  • Since there is no way to prevent exit() from ending the program, you will have to change the legacy application in some way or another.

    For a similar problem I used the following solution:

    • A class that provides the feature I want to use/change through a public, static function, e.g.
      static void Wrapper::exit( int exit_code);
    • A base class that declares the interface of the features I want to provide:
      virtual void Base::exit( int exit_code) = 0;
    • Then a class, derived from the base class Base, that implements the normal behaviour:
      void OsImpl::exit( int exit_code) { ::exit( exit_code); }
    • The Wrapper class finally contains a pointer to the implementation to use, by default an object of OsImpl, but that can be replaced by e.g. a TestImpl that does nothing.
      static void Wrapper::setImpl( Base* handler);
    • Finally, in the application replace ::exit( 0); by Wrapper::exit( 0);
      When run "normally", the application will stop as before, but in your test program you can make it return to the test function.

    I know this is quite condensed, but I hope you get the idea.