希望这是一个简单的问题。我有一个函数,它会不断提示用户输入(字符),并在满足特定条件下返回一个字符。我正在为此编写测试以及其他类似的函数,但不知道如何模拟用户输入。顺便说一下,我使用scanf()获取用户输入。
您可以使用freopen
来更改标准输入的行为,以从文件中读取。将测试输入放入文件中,在测试之前调用此函数。
freopen("filename", "r", stdin);
stdin
。 - Tugrul Atesecho -e "测试字符串\n另一个字符串" | ./a.out
echo
命令的字符串应按程序所需的顺序排列
cat test_str_file | ./a.out
test_str_file
文件应按程序所需的顺序包含测试字符串
另一方面,您可以将代码的输入部分替换为一些虚拟部分。如果您有单独的输入模块,则可以用虚拟模块替换它。
如果你在Unix或Cygwin上,你可以调用可执行文件并要求它使用文本文件作为标准输入。例如:
bash$ ./a.out < input_file
将验证移动到另一个函数中,并独立测试它。或者伪造用户输入,重构剩余部分以接受一个函数指针,该指针被回调以收集一些字母。这应该可以实现简单的伪造。
我已经很久没有写C了,但是类似这样的方法也可以起作用。
/* test this independentaly */
int isvalid(char* chars){
/* do stuff and return result */
}
/*real function */
char* getinput() {
scanf(....)
return stuff_from_scanf;
}
/*fake/mock function */
char* getinputFake(char * testString) {
return testString;
}
test() {
int result = isvalue(getinputFake("test data"));
/* rest of test */
}
你不需要测试scanf函数,但是你可以用fscanf替换它,并像这样传入字符流
stdin
char* getinput(FILE * stream) {
fscanf(stream....)
return stuff_from_fscanf;
}
test() {
FILE * stream = .....; /*create a dummy stream say from */
int result = isvalue(getinput(stream);
/* rest of test */
}
这是一个非常天真的解决方案,但它可能会做你想要的事情:
char getFakeUserInput()
{
static char* fakeInput = "This is some user input\n";
static int pos = 0;
if(pos >= strlen(fakeInput))
return '\0';
return fakeInput[pos++]
}
为什么不用默认值直接调用函数呢?