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/