简体   繁体   中英

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 . 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? If not, what are the alternatives?

Is it possible to create a FILE* in memory for the test?

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. 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.

Sidenote:

I'd like to avoid the test having to interact with the filesystem.

Why?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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