-1

In the code below I tried to explain my problem on a basic model.

class A
{
    public:
    A() {}
    virtual void foo() {}
    virtual ~A(){}
    //...
};
    

class B : public A{
    public:
    B(){}
    //...
    //does not contain the override function foo() 
};

class MustBeTested{
    public:
    MustBeTested(){
        //...    
    }
    void function()
    {
        m_elem->foo();
        //...
    }
    
    private:
    B* m_elem;
};


class Mock : public B {
    public:
    Mock() {}
    MOCK0(foo, void());
};

//test function from above class
void TestFunction
{
    Mock* dummy = new Mock;
    EXPECT_CALL(*dummy, foo()).Times(1);
    //i know it is wrong becase the called method is A::foo();
}


    

I have a basic class A that contains a virtual method. Derivative class B no longer contains the overwritten method foo (). The MustBeTested class contains the function to be tested, the class member is type B *. Initially without looking I started to make a Mock class derived from B to simulate EXPECT_CALL (). I realized that it is not possible because the method in A :: foo () will always be called.

My question is, if there is a workaround without making changes to the class A or B code?

Quarra
  • 2,527
  • 1
  • 19
  • 27
Ionut Alexandru
  • 680
  • 5
  • 17

1 Answers1

0

foo in B is not overriden, but it is there - with the default implementation from A. foo is virtual and can be overriden in classes that derive from B, like your Mock (that wouldn't be possible if foo was marked final in B). Your code will work if you will use dependency injection in MustBeTested, see Dependency injection with unique_ptr to mock.

Quarra
  • 2,527
  • 1
  • 19
  • 27