How to unit test c functions involving IO?

后端 未结 1 1083
野性不改
野性不改 2020-12-20 13:59

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

相关标签:
1条回答
  • 2020-12-20 14:31

    Mock getchar:

    1. 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());
      
    2. 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)

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

    0 讨论(0)
提交回复
热议问题