Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何为全局函数编写单元测试,其中使用C+中的gtest/gmock调用另一个全局函数+;?_C++_Unit Testing_Googletest_Gmock - Fatal编程技术网

C++ 如何为全局函数编写单元测试,其中使用C+中的gtest/gmock调用另一个全局函数+;?

C++ 如何为全局函数编写单元测试,其中使用C+中的gtest/gmock调用另一个全局函数+;?,c++,unit-testing,googletest,gmock,C++,Unit Testing,Googletest,Gmock,我有大约10个全局函数在文件中。需要为每个单元编写单元测试用例。可以从另一个全局函数调用全局函数 可以考虑以下三个全局函数: int bar(int n){ .......... //Could call another global function. .......... } int foo(int n){ .......... int b = bar(x); .......... } int hut(int n){ .......

我有大约10个全局函数在文件中。需要为每个单元编写单元测试用例。可以从另一个全局函数调用全局函数

可以考虑以下三个全局函数:

int bar(int n){
    ..........
    //Could call another global function.
    ..........
}

int foo(int n){
    ..........
    int b = bar(x);
    ..........
}

int hut(int n){
    ..........
    ..........  
    int a = foo(x);
    ..........
    ..........  
    int b = hut(y);
    ..........
    ..........
}
在测试hut()时,应该模拟函数foo()和bar()。foo()和bar()也可能发生同样的情况。我正在使用gtest和gmock。可以使用gtest和gmock吗


谢谢你的阅读

如果它们在同一个文件中,很遗憾,没有(理智的)方法来模拟这些全局函数。即使它们不是,您也很难做到这一点(例如,在构建单元测试代码时,将原始代码修改为
#包含
模拟头,而不是真实头),而且这将美观,因此我强烈建议您不要这样做

虽然需要添加全局模拟支持,但它只在创建模拟时有所帮助,不幸的是,它并没有解决“如何让我的函数调用模拟”的问题

它们在中涵盖了这一点,甚至提供了可能的解决方法—您可以通过某种方式重写代码,以“摆脱”静态全局函数,并使代码可测试


简言之:不,没有好的、简单的方法来模拟全局函数(特别是当它们调用其他全局函数时),您最好将代码重构为更易于测试的代码。

根据您的操作系统和工具链,您可以在googletest和链接器的帮助下实现这一点。它们是什么?Linux/GCC?Windows/VC++。。。?