c++ - 使用 GMOCK 在没有类文件的情况下模拟在 .cpp 中声明和定义的静态函数

标签 c++ static-methods googletest googlemock non-member-functions

file.h
int func(int);

file.cpp
static int call();
static void print(int x);

int func(int) {
    int val = call();
    print(val);
}

这里静态函数是在同一个文件file.cpp中声明和定义的。我在这里没有包含静态函数的定义。 现在使用 GMock 我需要模拟或测试 .h 和 .cpp 中定义的所有函数。

最佳答案

我能给出的唯一答案是 GMocks FAQ 中的答案。 :

My code calls a static/global function. Can I mock it?

You can, but you need to make some changes.

In general, if you find yourself needing to mock a static function, it's a sign that your modules are too tightly coupled (and less flexible, less reusable, less testable, etc). You are probably better off defining a small interface and call the function through that interface, which then can be easily mocked. It's a bit of work initially, but usually pays for itself quickly.

This Google Testing Blog post says it excellently. Check it out.

关于c++ - 使用 GMOCK 在没有类文件的情况下模拟在 .cpp 中声明和定义的静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17917102/

相关文章:

c++ - exit(int) 给出了错误的值

python - Django:如何在没有此类实例的情况下对另一个类进行反向外键查找?

c++ - 在对象上调用静态成员函数——有没有办法让它变成编译器错误?

c++ - 为什么编译器不识别 Google Mock 通配符?

c++ - 使用断言对函数进行单元测试

c++ - 为测试用例捕获系统日志

c++ - 为什么结构化绑定(bind)在 GCC 上失败?

c++ - 有效使用C++ iomanip库

python - 为什么使用python调用c++程序时静态变量没有释放

java - Java中如何使用静态扩展变量?