Search code examples
c++cstringoutputgoogletest

Get the last string printed in C/C++


I am trying to create a tester using googletest. the problem is that the function that I am testing is returning void and printing a result instead. I want to get the last string printed into the console so I can test the output. the string may include \n.

so I have the function itself:

void f_sequence(char sequenceStr[])
{
   //logic...
    if(condotion1)
        printf("somthing1");
    else if(condotion2)
        printf("somthing2")
(...)
}

and then the tester:

TEST(TesterGroup, TesterName)
{
    f_sequence("input");
    EXPECT_EQ("somthing1", /*how do i get the output?*/);
}

Is it possible?

The functions I test are in c, while the Test function itself (the tester) is in c++. the output is printed using printf. I cannot change the function itself. I am using CLion latest version.


Solution

  • Redirect the standard output to a buffer.

    Live on Coliru

    #include <stdio.h>
    #include <unistd.h>
    
    #define BUFFER_SIZE 1024
    int stdoutSave;
    char outputBuffer[BUFFER_SIZE];
    
    void replaceStdout()
    {
        fflush(stdout); //clean everything first
        stdoutSave = dup(STDOUT_FILENO); //save the stdout state
        freopen("NUL", "a", stdout); //redirect stdout to null pointer
        setvbuf(stdout, outputBuffer, _IOFBF, 1024); //set buffer to stdout
    }
    
    void restoreStdout()
    {
        freopen("NUL", "a", stdout); //redirect stdout to null again
        dup2(stdoutSave, STDOUT_FILENO); //restore the previous state of stdout
        setvbuf(stdout, NULL, _IONBF, BUFFER_SIZE); //disable buffer to print to screen instantly
    }
    
    void printHelloWorld()
    {
        printf("hello\n");
        printf("world");
    }
    
    int main()
    {
        replaceStdout();
        printHelloWorld();
        restoreStdout();
        // Use outputBuffer to test EXPECT_EQ("somthing1", outputBuffer);
        printf("Fetched output: (%s)", outputBuffer);
        return 0;
    }
    

    References: http://kaskavalci.com/redirecting-stdout-to-array-and-restoring-it-back-in-c/