Google Mock 单元测试静态方法 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8942330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Google Mock unit testing static methods c++
提问by Jonhtra
I just started working on unit testing (using BOOST framework for testing, but for mocks I have to use Google Mock) and I have this situation :
我刚开始进行单元测试(使用 BOOST 框架进行测试,但对于模拟我必须使用 Google Mock),我遇到了这种情况:
class A
{
static int Method1(int a, int b){return a+b;}
};
class B
{
static int Method2(int a, int b){ return A::Method1(a,b);}
};
So, I need to create mock class A, and to make my class B not to use real Method1 from A class, but to use mock.
因此,我需要创建模拟类 A,并使我的类 B 不使用 A 类中的真正 Method1,而是使用模拟。
I'm not sure how to do this, and I could not find some similar example.
我不知道该怎么做,也找不到类似的例子。
回答by B?ови?
You could change class B into a template :
您可以将 B 类更改为模板:
template< typename T >
class B
{
public:
static int Method2(int a, int b){ return T::Method1(a,b);}
};
and then create a mock :
然后创建一个模拟:
struct MockA
{
static MockCalc *mock;
static int Method2(int a, int b){ return mock->Method1(a,b);}
};
class MockCalc {
public:
MOCK_METHOD2(Method1, int(int,int));
};
Before every test, initialize the static mock object MockA::mock
.
在每次测试之前,初始化静态模拟对象MockA::mock
。
Another option is to instead call directly A::Method1
, create a functor object (maybe std::function type) in class B, and call that in the Method2. Then, it is simpler, because you would not need MockA, because you would create a callback to MockCalc::Method1 to this object. Something like this :
另一种选择是直接调用A::Method1
,在类 B 中创建一个函子对象(可能是 std::function 类型),然后在 Method2 中调用它。然后,它更简单,因为您不需要 MockA,因为您将创建一个对 MockCalc::Method1 的回调到此对象。像这样的事情:
class B
{
public:
static std::function< int(int,int) > f;
static int Method2(int a, int b){ return f(a,b);}
};
class MockCalc {
public:
MOCK_METHOD2(Method1, int(int,int));
};
and to initialize it :
并初始化它:
MockCalc mock;
B::f = [&mock](int a,int b){return mock.Method1(a,b);};