Google Mock单元测试静态方法C ++

编程入门 行业动态 更新时间:2024-10-22 16:51:15
本文介绍了Google Mock单元测试静态方法C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我刚刚开始进行单元测试(使用BOOST框架进行测试,但是对于模拟我必须使用Google Mock),并且我遇到这种情况:

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 :

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);} };

因此,我需要创建模拟类A,并使我的类B不使用真实的Method1

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.

我不确定该怎么做,也找不到类似的例子。

I'm not sure how to do this, and I could not find some similar example.

推荐答案

您可以将B类更改为模板:

You could change class B into a template :

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)); };

在每次测试之前,初始化静态模拟对象 MockA :: mock 。

Before every test, initialize the static mock object MockA::mock.

另一个选择是直接调用 A :: Method1 ,创建一个仿函数对象(也许是std :: function类型)在类B中,然后在Method2中调用它。然后,它变得更简单,因为您将不需要MockA,因为您将创建对此对象的MockCalc :: Method1的回调。像这样的东西:

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 :

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)); };

并对其进行初始化:

MockCalc mock; B::f = [&mock](int a,int b){return mock.Method1(a,b);};

更多推荐

Google Mock单元测试静态方法C ++

本文发布于:2023-10-31 04:52:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545059.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   单元测试   方法   Google   Mock

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!