Test printing functions in C - unit tests, check

Viewed 69

I'm trying to write unit test for C code using check. However, I have stumbled over tests for void methods without return statements, which only use printf(). How can I test the output from these methods? Is there any way to redirect the output to, i.e., an array of chars I can compare? I have found some answers for Python, but none for C.

1 Answers

Maybe try freopen()?

// untested, no guarantees
START_TEST(test_silentfunction) {
    // redirect stdout to file
    freopen("/tmp/OBSCURITY_fb78trerbwedftwefnwdfyutew.txt", "w", stdout);
    silentfunction();
    // return stdout to default tty output
    freopen("/dev/tty", "w", stdout);

    // check contents of file /tmp/OBSCURITY_fb78trerbwedftwefnwdfyutew.txt
    remove("/tmp/OBSCURITY_fb78trerbwedftwefnwdfyutew.txt");
}
END_TEST
Related