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

Call delete on a Mocked reference #56

Open Gerark opened 8 years ago

Gerark commented 8 years ago

Hello!

I have an interface that has to be injected into an object which is going to take the ownership of the interface pointer. Here's an example

class Interface { virtual ~Interface() {}; }

class Owner
{ 
public:
    Owner( Interface* interface ) 
    {
        this->interface = interface;
    }

    ~Owner()
    {
        delete interface;
    }

private:
    Interface* interface;
}
Mock<Interface> interface;
Owner* owner = new Owner(&interface.get());
When(Dtor(mockedPresentation)).AlwaysReturn();
delete owner;

During the

delete interface;

in the Owner destructor i got a crash in fakeit:

void *getCookie(int index) 
{
    return _firstMethod[-2 - index];
}

The index value is 0 if that could help. I'm not sure if I can treat the reference returned by Mock<>::get() as a heap allocated instance. Am I using the library in the wrong way?

xpac27 commented 8 years ago

Apparently this issue happens only on Visual Studio and is not happening on Win64 builds.

tnovotny commented 8 years ago

For me this works with mscv 2015 32 bit. I'm not sure whether it is a typo or an error, but you place the expectation for the destructor on mockedPresentation

When(Dtor(mockedPresentation)).AlwaysReturn();

and then go on to delete interfaces mock in the destrucor of owner. Maybe adding

Fake(Dtor(interface))

will help.

MiStroe commented 4 years ago

Hello,

I'm working with Visual Studio 2017 and I have the same issue. Usually I use smart pointer, but the outcome is the same. If I take ownership of an injected object, it can't be mocked in 32 bit environment. 64 bit works. I tried several things like compiler flags I read in other topics/issues, but nothing helped so far. But I have a feeling a compiler flag could resolve this.

ElJerry commented 4 years ago

Having the same issue here, I am only seeing this error on Win32, x64 works fine...