如何使用FILE*参数对C函数进行单元测试

her*_*ung 5 c file-io unit-testing

我有一个uint8_t command_read(const FILE* const in)可以读取的C函数in.我想为函数编写一个单元测试.是否有可能FILE*为测试创建内存,因为我想避免与文件系统交互?如果没有,有哪些替代方案?

小智 9

是否可以在内存中为测试创建FILE*?

当然.写作:

char *buf;
size_t sz;
FILE *f = open_memstream(&buf, &sz);

// do stuff with `f`

fclose(f);
// here you can access the contents of `f` using `buf` and `sz`

free(buf); // when done
Run Code Online (Sandbox Code Playgroud)

这是POSIX.文档.

阅读:

char buf[] = "Hello world! This is not a file, it just pretends to be one.";
FILE *f = fmemopen(buf, sizeof(buf), "r");
// read from `f`, then
fclose(f);
Run Code Online (Sandbox Code Playgroud)

这也是POSIX.

边注:

我想避免测试必须与文件系统进行交互.

为什么?

  • "*为什么?*" - 这是单元测试的本质.您希望在不涉及外部因素的情况下测试**模块功能**.这就是外部接口通常由存根或某种东西模拟的原因. (2认同)