c++unit-testingexitcppunit

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


I have a simple function which I want to test. The function goes like this:

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

Now I have to write a test which generates an error. Only the exit(1) exists the test with a failure, none the less!

How is this case usually handled?

I can rewrite/change the function code since I'm in full control of the entire project. However, I'm using cppunit and am hoping I can have that as one of the test in the suite.


Update:

One note that I'd like to make in regard to some of the solutions proposed: Added an interface that can be implemented differently depending on whether we are testing or not is not as strong a way to test as it may look like. Why is that? Because I would be testing with an interface which implementation is different in the test than in the real world. The result of the test does not prove that the real world situation would work right. At least not 100% (it only proves that the path is indeed taken in that particular situation.)


Solution

  • If you are using gtest, it has a whole section dedicated to it (see Death Tests), where they say :

    any test that checks that a program terminates (except by throwing an exception) in an expected fashion is also a death test.

    If you are using google test, then you can test for death test using ASSERT_DEATH.

    Otherwise, you need to spawn a process, execute a test, and check the result (return value of the spawned process).