[英]how can i test void method using google test framework
example: I have a void method which just prints the elements of an array.示例:我有一个 void 方法,它只打印数组的元素。
#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:为了在这种情况下正确测试该方法,我将 stream 注入该方法:
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.由于默认参数,调用者不必更改任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.