실습에서 제시된 테스트 방법은 아래와 같습니다.
istream 타입의 cin과 ostream 타입의 cout을 매개변수로 전달하여, 실행 후 콘솔 입력을 통해 출력을 확인할 수 있습니다.
// Lab2.h
namespace lab2
{
void PrintIntegers(std::istream& in, std::ostream& out);
void PrintMaxFloat(std::istream& in, std::ostream& out);
}
// main.cpp
#include <iostream>
#include "Lab2.h"
using namespace std;
int main()
{
lab2::PrintIntegers(cin, cout);
lab2::PrintMaxFloat(cin, cout);
return 0;
}
여기서 입력을 자동화하기 위해, 파일의 내용을 표준 입력(stdin)으로 전달하는 redirection을 이용할 수도 있습니다.
cmd> Lab2.exe < testinput.txt
위 2가지 방법 외에도 stringstream을 사용하여 테스트할 수도 있습니다. 이 방법은 아래 2가지 상황 때문에 가능합니다.
cin과 cout에 직접 의존하지 않고, istream과 ostream에 의존하도록 추상화되어 있습니다.istringstream은 istream을 상속받고, ostringstream은 ostream을 상속받습니다.이렇게 하면, 코드에 테스트 케이스 작성이 가능해져, assert 내에 string 비교로 빠르게 테스트 가능한 장점이 있습니다.
그러나 실제로 채점되는 환경은 표준 입출력이기에 stringstream과 표준 입출력간의 구현의 차이로 다른 결과가 나올 수 있다는 점에 주의해야 합니다.
#include "Lab2.h"
#include <cassert>
#include <sstream>
using namespace std;
int main()
{
// 1. PrintIntegers 테스트
{
istringstream is(
"52 102\\n"
" 1 abc 2382"
);
ostringstream os;
string expected(
" oct dec hex\\n"
"------------ ---------- --------\\n"
" 64 52 34\\n"
" 146 102 66\\n"
" 1 1 1\\n"
" 4516 2382 94E\\n"
);
lab2::PrintIntegers(is, os);
assert(os.str() == expected);
}
// 2. PrintMaxFloat 테스트
{
istringstream is(
"2.23\\n"
" -1912.87233125\\n"
" 2323 def 1"
);
ostringstream os;
string expected(
" + 2.230\\n"
" - 1912.872\\n"
" + 2323.000\\n"
" + 1.000\\n"
"max: + 2323.000\\n"
);
lab2::PrintMaxFloat(is, os);
assert(os.str() == expected);
}
return 0;
}