为什么在堆栈对象和堆对象上使用Times(n)调用gmock EXPECT_CALL时会得到不同的结果?

时间:2017-12-04 06:59:31

标签: c++ googletest googlemock gmock

我想在我的代码中使用带有Times(n)的gmock EXPECT_CALL。在调用使用new关键字创建的对象时,我编写了一个示例测试和 得到了错误的结果 但它与堆栈对象一起准确地工作。
由于我打算在实际测试中使用堆对象,我需要知道我在这里做错了什么。
这是我的示例代码。

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

class Point
{
private:
    int x;
    int y;

public:
    Point(int a, int b)
    {
        this->x = a;
        this->y = b;
    }

    virtual int getSum()
    {
        return x + y;
    }
};

class MockPoint :
        public Point
{
public:
    MockPoint(int a, int b):Point(a,b){}

    MOCK_METHOD0(getSum, int());
};

class PointTests :
        public ::testing::Test
{
};

TEST_F(PointTests, objectTest)
{
    MockPoint p(10, 20);
    EXPECT_CALL(p, getSum()).Times(10);
    p.getSum();
}

TEST_F(PointTests, pointerTest)
{
    MockPoint* p = new MockPoint(10,20);
    EXPECT_CALL(*p, getSum()).Times(10);
    p->getSum();
}

我希望两个测试都失败,因为我只调用了一次getSum()。

但这是我在运行测试时实际得到的结果。

[ RUN      ] PointTests.objectTest
/home/lasantha/test/PointTests.cpp:44: Failure
Actual function call count doesn't match EXPECT_CALL(p, getSum())...
         Expected: to be called 10 times
           Actual: called once - unsatisfied and active
[  FAILED  ] PointTests.objectTest (0 ms)
[ RUN      ] PointTests.pointerTest
[       OK ] PointTests.pointerTest (0 ms)
[----------] 2 tests from PointTests (0 ms total)

1 个答案:

答案 0 :(得分:1)

您必须删除MockPoint才能检查条件:

TEST_F(PointTests, pointerTest)
{
    MockPoint* p = new MockPoint(10,20);
    EXPECT_CALL(*p, getSum()).Times(10);
    p->getSum();
    **delete(p);**
}