[英]How to unit test a C function with a FILE* argument
我有一個C函數uint8_t command_read(const FILE* const in)
,它讀出in
。 我想為函數編寫一個單元測試。 是否可以在內存中為測試創建FILE*
,因為我希望避免與文件系統交互? 如果沒有,有哪些替代方案?
是否可以在內存中為測試創建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
這是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);
邊注:
我想避免測試必須與文件系統進行交互。
為什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.