I am facing problems in writing unit tests to C functions which involve IO operation. For example, below is the code I wrote to get an input string from the user from consol
Mock getchar
:
Utilizing preprocessor, e.g. in your test file.
#define getchar mock_getchar
#include "GetStringFromConsole.h"
...
const char* mock_getchar_data_ptr;
char mock_getchar()
{
return *mock_getchar_data_ptr++;
}
...
// in test function
mock_getchar_data_ptr = "hello!\n";
YourAssertEquals("hello", GetStringFromConsole());
Substitute symbol for the linker(harder, in my opinion), e.g. define your own getchar
somewhere in your source .c files instead of linking to a stdlib(e.g. msvcrt on windows)
Modify function under test to accept a function returning char
, best choice(IMHO) - no conflicts with stdlib. And setup a test by passing a thingy like mock_getchar
from point 1 in test code.
typedef char (*getchartype)();
char * GetStringFromConsole(getchartype mygetchar)
{
...
c = mygetchar()
For points 1 and 2 I'd propose to use your own function instead of getchar
(e.g. mygetchar
) - this way you could mock/substitute it without facing conflicts with std includes/libs.