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)
边注:
我想避免测试必须与文件系统进行交互.
为什么?