How to test code that writes to stdout?

前端 未结 1 395
半阙折子戏
半阙折子戏 2021-02-09 10:07

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(\"H         


        
相关标签:
1条回答
  • 2021-02-09 10:46

    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.

    0 讨论(0)
提交回复
热议问题