【问题标题】:Why do I get different results when calling gmock EXPECT_CALL with Times(n) on stack objects and heap objects?为什么在堆栈对象和堆对象上使用 Times(n) 调用 gmock EXPECT_CALL 时会得到不同的结果?
【发布时间】:2017-12-04 06:59:30
【问题描述】:

我想在我的代码中使用带有 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)

【问题讨论】:

  • 你永远不会删除堆上分配的模拟点,所以我假设它没有正确报告结果。也点缺少虚拟析构函数,似乎虚拟方法只是为了测试目的而添加的。
  • 谢谢。不删除堆对象是问题所在。添加虚拟析构函数并删除对象后解决了问题。感谢您的帮助。

标签: c++ googletest googlemock gmock


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 2016-02-27
    • 2015-03-28
    • 2010-12-08
    • 2020-08-24
    • 2020-04-09
    • 2020-10-27
    相关资源
    最近更新 更多