10

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?

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
qianchenglong
  • 474
  • 5
  • 13

1 Answers1

19

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.

Community
  • 1
  • 1
  • You know, just closing `stdout` might be bad. Not sure how CUNIT outputs its results... – Deduplicator Oct 01 '14 at 20:09
  • 3
    @Deduplicator - probably wouldn't be my first choice, but I don't know the constraints the OP is working under. Some of the SO answers I linked to had good ways to restore it or duplicate it. But I think those were closer to platform specific and didn't want to muddy my answer too much with them. –  Oct 01 '14 at 20:19
  • I wrote in windows.But I also use linux.So if there is an OS independent will be much better! – qianchenglong Oct 02 '14 at 03:28
  • @qianchenglong: Isn't standard C already platform independent? – Robert Harvey Oct 02 '14 at 17:22