2017-12-05 4 views
0

googletest를 사용하여 std :: cin을 통해 사용자 입력에 의존하는 함수를 테스트하려면 어떻게해야합니까?std :: cin을 통해 사용자로부터 입력을받는 googletest를 사용 하시겠습니까?

다음 예제에서는 readUserInput() 함수가 값 변수에 2를 읽도록 std :: cin 스트림에 "2 \ n"을 추가 할 수있는 코드를 찾고 있습니다. 사용자로부터의 입력이 필요합니다.

#include <iostream> 
#include "gtest/gtest.h" 

int readUserInput() 
{ 
    int value; 
    std::cout << "Enter a number: "; 
    std::cin >> value; 

    return value; 
} 

TEST(cin_test, Basic) 
{ 
    // need code here to define "2\n" 
    // as the next input for std::cin 

    ASSERT_EQ(readUserInput(), 2); 
} 

int main(int argc, char **argv) { 
    ::testing::InitGoogleTest(&argc, argv); 
    return RUN_ALL_TESTS(); 
} 

답변

2

하면 함수에 인수를 추가

int readUserInput(std::istream& input) 
{ 
    int value; 
    std::cout << "Enter a number: "; 
    input >> value; 
    return value; 
} 

TEST(Some, Test) { 
    std::ifstream ifs; 
    ifs.open("someFile", std::ifstream::in); 
    // in production code pass std::cin 
    std::cout << "readUserInput from std::cin: " << readUserInput(std::cin) << std::endl; 
    // in testing pass some mock data from the file (or whatever) 
    std::cout << "readUserInput from ifs: " << readUserInput(ifs) << std::endl; 
    ifs.close(); 
} 
관련 문제