如何gmock函数在同一个类当他们互相调用 [英] How to gmock functions in the same class when they call each other

查看:183
本文介绍了如何gmock函数在同一个类当他们互相调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设这里是这样:

  class base()
{
virtual func1 = 0;
virtual func2()= 0;
virtual func3()= 0;
}
class继承:public base
{
virtual func1(){func2(); func3()};
virtual func2(){/ * do something * /};
virtual func3(){/ * do something * /};
}



现在我想单元测试func1 func3(); func1()知道要调用mock-func2()和mock-func3(),因此可以模拟func2()和func3 )而不是调用真正的func2()和func3()?



通过我使用Class Factory的方式来初始化类,所以真实的情况可能有点多复杂



感谢〜

解决方案

描述,但它不漂亮。一种方法是使模拟从具体类而不是接口派生,并创建一个模拟的子类,它将根据一些配置成员将方法调用分派到适当的超类。例如:

  // MockBase类继承自BaseImpl,继承自
//'base'接口
类调度:public MockBase {
public:
void func1(){
return useMockFunc1? MockBase :: func1():BaseImpl :: func1();
}

bool useMockFunc1;
};

但是,这需要另一个类,要求你的模拟继承自具体的实现,而不是接口,并且它会使大多数程序员想用勺子挖出他们的眼睛。而不是使用这种可憎,可能值得审查你测试的类的设计,特别是寻找方法将它分解成单独的对象,每个都可以单独嘲笑。


Suppose here is the case:

class base()
{
   virtual func1()=0;
   virtual func2()=0;
   virtual func3()=0;
}
class Inheritance:public base
{
   virtual func1(){ func2(); func3() };
   virtual func2(){ /* do something */ };
   virtual func3(){ /* do something */ };
}

now I want to unit test func1(), and mock func2() and func3();

so is it possible to mock func2() and func3() while func1() knows to call the mock-func2() and mock-func3() and not call the real func2() and func3()?

by the way I use Class Factory to init the class, so the real case may be a little more complicated

thanks~

解决方案

It's definitely possible to do what you describe, but it's not pretty. One way of doing it is to have the mock derive from the concrete class instead of the interface, and create a subclass of the mock that will dispatch method calls to the appropriate superclass depending on some configuration member. For example:

// class MockBase inherits from BaseImpl, which in turn inherits from
// the 'base' interface
class Dispatch : public MockBase {
public:
    void func1() {
        return useMockFunc1 ? MockBase::func1() : BaseImpl::func1();
    }

    bool useMockFunc1;
};

However, this requires yet another class, mandates that your mock inherit from the concrete implementation rather than the interface, and it would make most programmers want to dig their eyes out with a spoon. Rather than using this kind of abomination, it would probably be worthwhile to review the design of the class that you're testing, specifically looking for ways to decompose it into separate objects, each of which could be mocked individually.

这篇关于如何gmock函数在同一个类当他们互相调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆