eranpeer / FakeIt

C++ mocking made easy. A simple yet very expressive, headers only library for c++ mocking.
MIT License
1.24k stars 170 forks source link

Support for stubbing "protected" virtual methods #62

Open AbdelghaniDr opened 8 years ago

AbdelghaniDr commented 8 years ago

Hi, I wonder if there is a way to stub a protected virtual method using a spy object or does this library work only on public methods ?? I'm using VS2015 Thanks

jksf commented 8 years ago

I have the same exact problem. Is there any way to mock protected virtual methods? I enjoy this library but lack of this feature prevents me from testing classes that use Template Method design pattern.

tnovotny commented 8 years ago

C++ compilers prevents this. The only way to do it is to derive an Interface that makes them public again:

class Nvi
{
public: 

    void foo()
    {
        _foo();
    }

protected:

    virtual void _foo() = 0;

};

class NviTest
    : public Nvi
{
public:

    virtual void _foo()
    {
    }
};
bu5hm4nn commented 6 years ago

There is a simple and sneaky way of getting to private and protected members for testing. Just define these when compiling tests:

// Get access to private members for testing
#define private public
#define protected public
hedayat commented 1 year ago

Actually, there is a way to access protected/private members. I've implemented such a feature for FakeIt here, which is actually mostly independent from the library itself.

I'm not sure if it is 'clean enough', but I hopefully will take a look to see if this feature can be implemented inside FakeIt itself properly. I guess it is possible, so if anybody is interested it can do it sooner than me.