Search code examples
ccunit

How to test code that writes to stdout?


How to write a test in CUnit for a function that prints to stdout, to verify its output?

Example function to test:

void print()
{
    printf("Hello world");
}

Its unit test should somehow verify that "Hello world" was printed to the console:

void test_print()
{
    // how to assert?
}

How should I go about it?


Solution

  • This ought to achieve what you're looking for.
    (ie. how to tell that something was written to stdout)

    #include <sys/stat.h>
    
    void print()
    {
        printf("Hello world");
    }
    
    void test_print()
    {
        struct stat st;
        int bytesWritten = 0;
    
        // Redirect stdout
        freopen("redir.txt", "w", stdout)
    
        print();
    
        // assert checking
        stat("redir.txt", &st);
        bytesWritten = st.st_size;
    
        CU_ASSERT( bytesWritten < 0 );
    }
    

    Note that this ruins your ability to restore stdout, but that's a known problem In the link, they suggest a means to use a FILE pointer and use fprintf() instead of printf()


    stdout redirect example borrowed from here

    File Size checking borrowed from here

    And here's a reference link from CUNIT

    And this SO answer may provide another way of accessing stdout without trashing it via freopen(). Or this SO answer to revert the redirect.


    Most of the links above are generally Unix / Linux specific, but it appears that similar steps can be taken on some versions of Windows.

    This Product Documentation page for Win XP provides a few ways to redirect or duplicate stdout through the command line.

    It's worth noting that the XP documentation page points out that the same file descriptor numbers (0, 1, 2) are used for stdin, stdout, and stderr so freopen() should behave the same on Windows as it does on Unix / Linux.