0

我一直在寻找答案,但我没有找到答案。问题是,我需要为我用 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:

有没有办法完全忽略所有用户输入,或者定义我的测试用例将使用的未来用户输入?

谢谢!

4

2 回答 2

0

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

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

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

于 2014-12-18T18:07:34.323 回答
0

您可以轻松地为您的单元测试编写自己的 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));
}
于 2014-12-18T20:55:47.770 回答