C - 忽略CUnit中的用户输入?

时间:2014-12-18 17:48:12

标签: c testing input cunit

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

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

谢谢!

2 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分: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));
}