how to test static functions of C using google test

自闭症网瘾萝莉.ら 提交于 2019-12-11 11:55:46

问题


I have a C file contains some static functions, how to use google test to test those static function?

header file:

test.h
int accessData();

source file:

test.c
static int value;
static int getData()
{
   return value;
}

int accessData()
{
    if(value != 0)
    {
       return getData();
    }
    return 0;
}

static function is called by global function, but how to test those static function using google test?


回答1:


One way to achieve this is to #include the C source file into your test source. Then, the static function is part of the same translation unit as the test code, and can be called from it:

#include "test.c"

/* here follow the tests of getData() */

The downside to this is that everything in test.c gets compiled again, with obvious impact on build times. If that gets to be a problem, you might consider extracting the static functions to be tested into their own source file (e.g. test_p.c, with the _p meaning private/internal). Then #include "test_p.c" from both test.c and your unit test.




回答2:


I understand that to test a function with google test, it must be visible to the test code. A static function is only visible to the current compilation unit.

A way to get around this is to "remove" the static attribute for test purposes:

#ifndef GOOGLE_TEST
# define STATIC static
#else
# define STATIC
#endif

STATIC int getData();

If this gives conflicts, for example because there aer getData() functions in many source files, you could create simple container functions:

static int getData(<arglist>);

#ifdef GOOGLE_TEST
int myModule_getData(<arglist>) {return(getData(<arglist>);}
...
#endif



回答3:


A static function has it's visibility limited to the translation unit.

AFAIK, for googletest, you need to call the function(s) under test from a separate test file conating the test code written with TEST(). If the function under test is static, simply it is not possible to test that directly from the TEST() MACRO invocation.

The straightway approach is to, comment out the static modifier for the function for testing purpose.



来源:https://stackoverflow.com/questions/32094797/how-to-test-static-functions-of-c-using-google-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!