0

In the following example, I would like to check if fooFunction is called upon destruction of the object.

#include <gtest/gtest.h>
#include <gmock/gmock.h>

class FooClass
{
public:

    ~FooClass(){ FooClass::fooFunction(); }
    virtual void fooFunction() {}
};

class MockFooClass : public FooClass
{
public:
    MOCK_METHOD0(fooFunction, void());
};

TEST(DumbTest, blabla)
{
    auto mock = new MockFooClass;
    EXPECT_CALL(*mock, fooFunction());
    delete mock;
}

However this test fails because the destructor of FooClass calls FooClass::fooFunction() instead of MockFooClass::fooFunction(). Does anyone know of a way to do that?

I'm using Visual Studio 2010.

I understand why this test fails: as soon as we enter the destructor of FooClass, the object is not a MockFooClass any more. What I'm looking for is if anyone knows of a way to get around it.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Thomas Benard
  • 200
  • 1
  • 3
  • 10
  • 1
    I think you're confused about when destructors are called. When ~FooClass is called, it's no longer a MockFooClass – UKMonkey Apr 20 '18 at 12:57
  • Possible duplicate of [Calling virtual function from destructor](https://stackoverflow.com/questions/12092933/calling-virtual-function-from-destructor) – Andrew Kashpur Apr 20 '18 at 13:00
  • @UKMonkey Yes, that's precisely my problem ! I understand why it fails, I have no problem with that. What I'm looking for is a way to check the function has really been called. Maybe it's a dumb question, and it is simply not possible in C++. I'm just trying to find out if there's any way to do it. – Thomas Benard Apr 20 '18 at 13:05
  • Have your mock method set a variable and check that variable? It's not going to ever be called though, so you're really just writing a unit test for the compiler. – UKMonkey Apr 20 '18 at 13:12
  • Two people told you it is not possible to do what you want to do :) – BЈовић Apr 20 '18 at 13:22
  • On the other side, why are you mocking a class that you try to test? This seems to be the main problem. We generally use mocks to provide independence from **other class** implementation. It doesn't make sense to test a mock. – Yksisarvinen Apr 20 '18 at 13:54
  • Shouldn't the destructor be `virtual`? – BartoszKP Apr 20 '18 at 22:25

1 Answers1

0

You can use Isolator++ to use check that the method was called.

class FooClass
{
public:

    ~FooClass(){ FooClass::fooFunction(); }
    virtual void fooFunction() {}
};


TEST(DumbTest, blabla)
{
    auto real = new FooClass;
    auto mock = FAKE_ALL<FooClass>(FakeOptions::CallOriginal);
    delete real;
    ASSERT_WAS_CALLED(mock->fooFunction());
}
Sam
  • 182
  • 6