首页 > 解决方案 > 如何将 unique_ptr 作为函数参数传递给模拟对象

问题描述

我正在尝试使用gtest / gmock向我的项目添加一些测试。const unique_ptr我在测试一个接受另一个类的对象的函数时遇到问题。

View有一些功能,包括get_description_from_user()get_category_from_user()。这些函数获取用户在终端窗口中输入的数据。在类PlanService中有一个create_plan()从类调用上述函数的函数View。我创建了一个MockView类,但我不知道如何将指向此类对象的指针作为create_plan()函数的参数传递。

这是我的代码:

class MockView :
        public View {
public:
    MOCK_METHOD(string, get_description_from_user, ( ));
    MOCK_METHOD(string, get_category_from_user, ( ));
};

TEST(create_plan, set_category_and_description)
{
    const unique_ptr<MockView> view(new MockView());
    EXPECT_CALL(*view, get_description_from_user()).WillOnce(Return("desc"));
    EXPECT_CALL(*view, get_category_from_user()).WillOnce(Return("cat"));

    PlanService plan_service;
    plan_service.create_plan(move(view)); //The problem is here.
    EXPECT_EQ(plan_service.get_category(), "cat");
    EXPECT_EQ(plan_service.get_description(), "desc");
}

我收到一个错误:

no matching function for call to  ‘PlanService::create_plan(std::remove_reference<const  std::unique_ptr<MockView>&>::type)’ plan_service.create_plan(move(view));

非常感谢您的任何帮助。

编辑:PlanService

#include <memory>
#include <vector>

class Plan;
class View;

class PlanService {

public:
    PlanService() = default;
    virtual ~PlanService() = default;
    virtual void create_plan(const std::unique_ptr<View>& view);
    //... some more functions
    const std::string& get_description() const;
    const std::string& get_category() const;
private:
    std::string description;
    std::string category;
};

函数定义create_plan()

void PlanService::create_plan(const unique_ptr<View>& view)
{
    description = view->get_description_from_user();
    category = view->get_category_from_user();
}

View要复杂得多,因为它使用了ncurses库,所以我不添加这个类的实现。

标签: c++googletestgooglemock

解决方案


推荐阅读