如何为另一个使用stdin输入的函数编写测试函数?

Ash*_*Ash 3 c stdin unit-testing

作为大学任务的一部分,我有以下功能:

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;
}
Run Code Online (Sandbox Code Playgroud)

它非常适合我需要它做的事情(从键盘输入).我必须使用stdin(就像我一样),因为我的教授提出了许多要求.

我想为作业编写一系列"单元测试",但我不知道如何调用我的测试函数readMenuOption()并将输入传递给它(无需在运行时进行).

这是可能的,如果可以的话,我该怎么做?(即,是否可以写入标准输入)?

pax*_*blo 5

可以做的一件事就是简单地修改readStdin以允许它从真实标准输入或辅助函数获取数据,例如:

char *fakeStdIn = "";
int myfgetc (FILE *fin) {
    if (*fakeStdIn == '\0')
        return fgetc (fin);
    return *fakeStdIn++;
}

int readStdin(int limit, char *buffer) 
{
   char c;
   int i = 0;
   int read = FALSE;
   while ((c = myfgetc(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;
}
Run Code Online (Sandbox Code Playgroud)

然后,要从单元测试中调用它,您可以执行以下操作:

fakeStdIn = "1\npaxdiablo\nnice guy\n";
// Call your top-level input functions like  readMenuOption().
Run Code Online (Sandbox Code Playgroud)

通过在较低级别放置一个钩子,您可以注入自己的字符序列而不是使用标准输入.如果在任何时候,假的标准输入已经耗尽,它将恢复为真实的输入.

显然,这是使用字符,所以,如果你想要注入EOF事件,你需要一个整数数组,但这将是对该方案的一个小修改.