EXPECT_CALL用于参数类型为unique_ptr引用的模拟函数

时间:2018-06-20 22:53:15

标签: c++ unit-testing googlemock gmock

我要对以下功能进行单元测试:

void
MyClass::add(const Shape& shape)
{
   std::unique_ptr< Line> line;
   if (m_DataBase.getLine(shape->getId(), line).ok())
   {
      addEntry(line->getDimensions());
   }
}

为此,我需要模拟DataBase类的getLine函数:

class DataBase
{
 public:
   virtual Result getLine(const ShapeId& shapeId, const std::unique_ptr< Line >& line) = 0;
...
}

DataBase类模拟:

class DataBaseMock
{
 public:
   MOCK_METHOD2(getLine, Result(const ShapeId& shapeId, const std::unique_ptr< Line >& line));
...
};

MyClass :: add函数测试如下:

MyClassTest::MyClassTest{
    DataBaseMock m_DataBaseMock;
    std::unique_ptr< MyClass> m_MyClass;
}

void MyClassTest::setUp(){
    m_MyClass = std::unique_ptr< MyClass >(new MyClass(m_DataBaseMock));
}

void MyClassTest::Test_Add()
{
   Shape shape;
   std::unique_ptr <Line> line = std::unique_ptr <Line> (new Line());

   EXPECT_CALL(m_DataBaseMock, getLine(_,_)).WillOnce(DoAll(SetArgReferee< 1 >(line), Return(Result::OK);
   CPPUNIT_ASSERT_NO_THROW(m_MyClass->add(shape));
}

虽然以上代码在getLine函数将shared_ptr作为参数时有效,但在unique_ptr的情况下,EXPECT_CALL行出现以下错误:

error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Line; _Dp = std::default_delete<Line>]'
    EXPECT_CALL(m_DataBaseMock, getLine(_,_)).WillOnce(DoAll(SetArgReferee< 1 >(line), Return(Result::OK);

1 个答案:

答案 0 :(得分:1)

解决方案由技巧组成,即将getLine()方法委托给不采用仅移动callGetLine()参数的模拟方法(我们称其为std::unique_ptr):

MOCK_METHOD2(callGetLine, Result(const ShapeId& shapeId, Line* line));
Result getLine(const ShapeId& shapeId, const std::unique_ptr< Line >& line) {
    return callGetLine(shapeId, line.get());
}

请注意,无需在基类中定义或声明callGetLine()。您只需要在模拟类中将其定义为MOCK_METHOD

现在,您可以在callGetLine()方法上设置期望值了。

EXPECT_CALL(m_DataBaseMock, callGetLine(_,NotNull()).WillOnce(Return(Result::OK));