Unit tests for C++ criterion

With gtest, I think this can help you

testing::internal::CaptureStdout();
std::cout << "My test";
std::string output = testing::internal::GetCapturedStdout();

refer from : How to capture stdout/stderr with googletest?


The other answer shows how to use a googletest facility. However, in general when your code is difficult to test, then that is a code smell. Consider this simpler example:

void foo(){
    std::cout << "hello";
}

This is much easier to test when don't use std::cout directly, but pass the stream to be used as parameter:

#include <iostream>
#include <sstream>

void foo(std::ostream& out){
    out << "hello";
}
    
int main() {
    std::stringstream ss;
    foo(ss);
    std::cout << (ss.str() == "hello");
}

In general, I do not recommend to use std::cout directly for anything but small toy programs. You never know if later you want to write to a file or some other stream.