Ethan
Ethan

Reputation: 79

How to gmock functions in the same class when they call each other

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~

Upvotes: 1

Views: 1217

Answers (1)

Ian
Ian

Reputation: 872

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.

Upvotes: 1

Related Questions