eranpeer / FakeIt

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

Dynamic casting of Mocked objects not working #41

Closed hartness closed 9 years ago

hartness commented 9 years ago

If I try to dynamic cast the underlying smart pointers to mocked objects it doenst work. The result is always null.

E.G. class IBase { public: virtual void methodA() = 0; };

class Base : public IBase
{
public:
    void methodA() override
    {
        cout << "Base::methodA";
    }
};

class Derived : public Base
{
public:
    void methodA() override
    {
        cout << "Derived::methodA";
    }
};

Mock<Derived> mock;

When(Method(mock, methodA)).AlwaysReturn();

Derived& derived = mock.get();

struct DoNotDelete { void operator()(Derived* p) const { } };
shared_ptr<Derived> derivedSPtr = shared_ptr<Derived>(&derived, DoNotDelete());

//This version works #1
//shared_ptr<Derived> derivedSPtr(new Derived());

set<shared_ptr<Base>> set;

set.insert(derivedSPtr);

for (auto item : set)
{
    shared_ptr<Base> b1 = item;
    b1->methodA();

    shared_ptr<Derived> d1 = dynamic_pointer_cast<Derived>(b1);

//Next line fails. //d1 is always null for the mocked version. If a real Derived object is used like the line commented out above #1 it works fine.

    d1->methodA();
}
hartness commented 9 years ago

Looks like this is not a bug at all. I've discovered that I can fix this issue by declaring my mock like this:

Mock<Derived, Base> mock;

Doing this fixes the issue and allows correct casting from base to derived mocked classes.

hartness commented 9 years ago

Doh!!