example: I have a void method which just prints the elements of an array.
#include <stdio.h>
void PrintNumbers();
int arr[10];
int main(){
int i;
int value = 0;
for(i = 0 ; i<10; i++)
arr[i] = value++;
PrintNumbers();
return 0;
}
PrintNumbers(){
int i;
for(i = 0 ; i < 10 ; i++)
cout <<"arr["<< arr[i] << "]" << endl;
}
To have the method tested properly in this case, I'd inject the stream to the method:
void PrintNumbers(std::ostream& os = std::cout) {
int a = 42;
os << "Expected " << a;
}
TEST(PrintNumbersTest, TestWithStringStream) {
std::stringstream myStream;
PrintNumbers(myStream);
ASSERT_EQ("Expected 42", myStream.str());
}
Dependency injection is one of the options here and is widely acceptable. Because of the default argument, the caller doesn't have to change anything.