【问题标题】:C - Ignoring user inputs in CUnit?C - 忽略 CUnit 中的用户输入?
【发布时间】:2014-12-18 17:48:11
【问题描述】:

我一直在寻找答案,但没有找到答案。问题是,我需要为我用 C 编写的程序做一些测试用例。问题是,一些函数接受用户输入,这使我的测试用例等待输入,这不是我想要的。

这是我的一个测试用例:

void test_is_location_free() {
  Storage test_storage = new_storage();
  Item test_item;
  test_storage->inventory[5] = test_item;
  test_storage->inventory[5].loc.shelf = 'A';
  test_storage->inventory[5].loc.place = 1;

  CU_ASSERT(!is_location_free(test_storage, test_item, 'A', 1));
}

这是可行的,因为 is_location_free() 将返回 false,但在函数内部我有另一个函数会不断询问用户新的输入,直到所选位置空闲。

这是它在终端中的样子,它将等待新的用户输入货架:

Suite: HELPER FUNCTIONS
  Test: compare_char() ...passed
  Test: first_empty_position() ...passed
  Test: is_location_free() ...Location not empty, try again!
Shelf:

有什么方法可以忽略所有用户输入,或者定义我的测试用例将使用的未来用户输入?

谢谢!

【问题讨论】:

  • 您可以使用 #define TESTING 然后 #ifdef TESTING ... #else ... #endif 将输入替换为准备好的静态数据。
  • 是的,可以做到。当涉及到测试用例时,这是一个可以使用的替代方案吗?我只是认为 CUnit 应该对这些类型的情况有某种支持!

标签: c testing input cunit


【解决方案1】:

假设您的代码从标准输入流中获取用户输入,您可以将数据写入文件并在调用 is_location_free 函数之前临时更改标准输入以从该文件中读取。

我认为如果从终端(/dev/tty)读取用户输入,同样的想法可能会奏效,但需要更多的努力。

注意:在这种特殊情况下,我建议只重构您的代码,以便 is_location_free 函数只执行其名称所暗示的功能。然后就很容易测试了。编写第二个函数以添加在第一个位置不起作用时提示用户的行为。您可以选择不对第二个函数进行 CUnit 测试。

【讨论】:

  • 是的,这些功能有点混乱,其中包含所有这些用户输入。我在函数中使用 fgets() 和 stdin,但我不确定在调用它之前如何更改它。无论如何,我认为最好的办法是重构整个代码。谢谢!
  • 只要你不需要回到原来的标准输入流,freopen 函数就可以解决问题。这是有关该主题的更多讨论的链接:link
  • “不要将形式与功能混为一谈。”
  • 这里有一个类似的问题:5740176
【解决方案2】:

您可以轻松地为您的单元测试编写自己的 fgets() 版本。这称为模拟,在单元测试中很常见。这样的事情应该可以工作:

static char test_input[MAX_INPUT];

char *fgets(char *s, int size, FILE *stream)
{
  strncpy(s, test_input, size);

  return s;
}

然后像这样重写你的测试:

void test_is_location_free() {
  Storage test_storage = new_storage();
  Item test_item;
  test_storage->inventory[5] = test_item;
  test_storage->inventory[5].loc.shelf = 'A';
  test_storage->inventory[5].loc.place = 1;

  strncpy(test_input, "test input data", MAX_INPUT);

  CU_ASSERT(!is_location_free(test_storage, test_item, 'A', 1));
}

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    相关资源
    最近更新 更多