简体   繁体   English

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

[英]How to unit test a C function with a FILE* argument

I have a C function uint8_t command_read(const FILE* const in) that reads from in . 我有一个C函数uint8_t command_read(const FILE* const in) ,它读出in I would like to write a unit test for the function. 我想为函数编写一个单元测试。 Is it possible to create a FILE* in memory for the test since I would like to avoid having to interact with the filesystem? 是否可以在内存中为测试创建FILE* ,因为我希望避免与文件系统交互? If not, what are the alternatives? 如果没有,有哪些替代方案?

Is it possible to create a FILE* in memory for the test? 是否可以在内存中为测试创建FILE *?

Sure. 当然。 For writing: 写作:

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

This is POSIX. 这是POSIX。 Docs. 文档。

For reading: 阅读:

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);

This is POSIX too. 这也是POSIX。

Sidenote: 边注:

I'd like to avoid the test having to interact with the filesystem. 我想避免测试必须与文件系统进行交互。

Why? 为什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM