I started writing a little program in C as a development excercise and I want to have a lot of unit test for this programs. The problem is that from time to time it uses fread/fwrite and other standard functions – I don’t want my unit tests to open any file, so it would be great if I could write stub for fread/fwrite.
Anyone have solution for this problem?
Thanks in advance for answers!
edit: I forgot about one important thing: stub for read need to behave differently in different tests. In one, read return value must be < then passed number of elements to read (simulates too early eof) and in other read return value must be equal to passed number of elements to read
There are multiple options:
fopen(),fread(), etc into indirect function calls, through function pointers. For normal operation set them to point tofopen(), etc. For testing, set them to point to your functions.myfopen(),myfread(), etc. Compile the main part of the program with the macros namedfopen,fread, etc and expanding intomyfopen,myfread, etc.fopen(),fread(), etc. Play with the linker to make them replace the ones from the standard library. This is very error-prone and hard to do.fopen(),fread(), etc functions using disassembly, assembly and run-time code patching. This isn’t easy either.