How do you write a test against a function that calls exit ()?

I have a simple function that I want to test. The function is performed as follows:

void func()
{
    // do some work
    ...
    if(error_detected)
    {
        fatal_error("failure...");
        exit(1);
    }
}

Now I need to write a test that generates an error. Only output (1) does the test fail, however!

How is this case usually handled?

I can rewrite / change the function code, since I have full control over the entire project. However, I am using cppunit and hope that I will succeed as one of the tests in the package.


Update:

, : , - , , , , , ? , , . , . , 100% ( , .)

+4
4

gtest, , (. Death Tests), :

, , ( ) , .

Google, ASSERT_DEATH.

, ( ).

+3

, , .

: , , HTTP- . , , , , , HTTP 4XX ( ), (.. exit() ).

, :

void func()
{
    // do some work
    ...
    if(error_detected)
        throw std::runtime_error("failure..."); // no exit call at all
}

( , exit):

try { func(); } catch(const std::runtime_error&) { exit(1); }

( ):

try {
    func();
    // mark test as failed here (should not be reached)
} catch(const std::runtime_error&) {
    // mark test as passed here
}

(, C ), :

typedef void (*on_error)(int error_code);
void func(on_error callback)
{
    // do some work
    ...
    if(error_detected)
        callback(1);
}

:

void exit_on_error(int code) { exit(code); }
func(exit_on_error);

:

enum { no_error = 0 };
int failed = no_error;
void on_error(int code) { failed = code; }

// test code:
func(on_error);
// check value of failed here
+4

, , exit(), .

void func(IApplicationServices& app) {
   // ...
   app.exit();
   // ...
}

, , , . , , .

, , , , , .

+3

You can override the function exit, perhaps for the duration of this particular test. See Wrapping Functions for the Linux Common Library .

+2
source

Source: https://habr.com/ru/post/1543038/


All Articles