Search code examples
c++cppunit

Checking printf output in CppUnit


Let's say I have a simple HelloWorld class with a hi() method with the following single line of code:

void HelloWorld::hi(){
    printf("Hi!\n");
}

Now let's say I want to test that method with CppUnit.

void HelloWorldTests::testHi() {
    HelloWorld hw;
    hw.hi(); // <------ ????
    // <------ ?????
    CPPUNIT_ASSERT(/*????*/);
}

How would I catch the output of the hi() method so that I can compare it to a fixed value in CppUnit?


Solution

  • There is no standard way to capture the output to stdout within a program. You can redirect the output to stdout to a file using freopen(filename, "w", stdout) and then compare the content of the file. The main problem with this approach is that there is no standard approach to restore the original destination.

    I'd recommend changing the code to use std::cout instead as this can be easily redirected to a suitable std::streambuf, e.g., an std::stringbuf, using the rdbuf() member. The original stream buffer can be kept and restored once the method writing to std::cout is done:

    struct HelloWorld {
        void hi() {
            std::cout << "hi";
        }
    };
    
    bool test_hi() {
        std::ostringstream out;
        std::streambuf* orig_buf(std::cout.rdbuf(out.rdbuf()));
    
        HelloWorld hw;
        hw.hi();
    
        std::cout.rdbuf(orig_buf);
    
        return out.str() == "hi";
    }