【发布时间】: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