我有以下功能作为学院任务的一部分:如何为使用stdin输入的其他函数编写测试函数?
int readMenuOption()
{
/* local declarations */
char option[2];
/* read in 1 char from stdin plus 1 char for string termination character */
readStdin(1 + 1, option);
return (int)option[0] <= ASCII_OFFSET ? 0 : (int)option[0] - ASCII_OFFSET;
}
int readStdin(int limit, char *buffer)
{
char c;
int i = 0;
int read = FALSE;
while ((c = fgetc(stdin)) != '\n') {
/* if the input string buffer has already reached it maximum
limit, then abandon any other excess characters. */
if (i <= limit) {
*(buffer + i) = c;
i++;
read = TRUE;
}
}
/* clear the remaining elements of the input buffer with a null character. */
for (i = i; i < strlen(buffer); i++) {
*(buffer + i) = '\0';
}
return read;
}
它完美地为我需要做的(以输入从键盘)。由于我的教授列出了一些要求,我必须使用stdin(就像我)那样做。
我想为该任务编写一系列“单元测试”,但我不知道如何让我的测试函数调用readMenuOption()
并将输入传递给它(而不必在运行时执行)。
这是可能的,如果是这样,我该怎么做? (即,是否可以写入标准输入)?
可能重复[如何单元测试涉及IO的c函数?](http://stackoverflow.com/questions/14028950/how-to-unit-test-c-functions-involving-io) – Valryne 2015-10-04 13:15:59