Google Mock and pointers in the test

Hi

Could someone explain me what is going on in this test:

SimpleTest.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "gmock/gmock.h"

class SimpleTest : public ::testing::Test {

protected:
    class MyInterface {
        virtual void doSomething()=0;
    };

    class MyMock : public MyInterface {
    public:
        MOCK_METHOD0(doSomething,
                     void());
    };

};

SimpleTest.cpp

1
2
3
4
5
6
#include "SimpleTest.h"

TEST_F(SimpleTest, simpleTest) {
    MyMock *myMock = new MyMock;
    EXPECT_CALL(*myMock, doSomething()).Times(1);
}


So this test passes, despite the fact that nobody called doSomething function. But If I change my test to
1
2
3
4
TEST_F(SimpleTest, simpleTest) {
    MyMock myMock;
    EXPECT_CALL(myMock, doSomething()).Times(1);
}

test fails as expected.

What is going on here?
Last edited on
You leak myMock in the first example and you don't in the second. It is the destructor of the Mock object that reports the results. In the first, that destructor is never invoked.
Thank you. It looks like I need additional information about this.

Could you explain what do you mean by "leak". I understand it is something with references and points.
Could you explain what do you mean by "leak".

When an invocation of new is not followed at some point by feeding the result of said invocation to the corresponding version of delete, you have leaked memory and whatever resources are managed by the object that resides in that memory.

If you feel the need to use new, you should look into smart pointers.
Topic archived. No new replies allowed.