Globally suppress c ++ std :: cout when testing

I have a Struct point for numeric data using the returnNext () method that returns AND to stdout the next anchor point called each time. I also have a series of unit tests that use this method: in these tests, I want to suppress all std :: cout data so that I can validate the return values ​​without bloating the screen with messages. eg.

struct Data { 
  Data(int n): datum{n} {};
  int datum;
  int returnNext() { 
    std::cout << datum << " returned" << std::endl;
    return datum;
  }
}

// main.cpp
int main() {
  Data d{100};
  d.returnNext(); // I want this to print at the screen 
  return 0;
}

// test.cpp
int main() {
  TEST( ... ) {
    Data d{100};
    ASSERT_THAT(d.returnNext(), 100); // I want just to check the output, not to check
  }
std::cout << "some message" << std::endl; // I want this printed
return 0;
}

      

An obvious solution would be to use flags / commands before the compiler to exclude std :: cout from the TEST build. But that would require editing multiple modules and would also make my code ugly.

Another case would be using redirect stdout for dev / null from the console, but this will also suppress stdout in my test units.

Isn't there a way to programmatically suppress / redirect stdout at specific points in a program's lifetime?

+3


source to share


3 answers


For a general suppression problem, std::cout

you can use std::basic_ios::rdbuf

with a null buffer:



std::cout.rdbuf(nullptr);

      

+11


source


This is why having hard-coded stdout output in your member functions is a bad idea. Now you think you need to block std::cout

globally because the behavior of your class is inflexible.



Instead, move the call to std::cout

someplace else (to make its use optional) or let it be arbitrary std::ostream

, which you can do nowhere.

+3


source


Try to close stdout fd:

close(1);

      

-2


source







All Articles