如何模拟返回对象

时间:2020-01-30 09:46:16

标签: c++ unit-testing googletest gmock

我尝试模拟User类及其嵌套结构UserBuilder:

class User
{
  public:
        virtual int loadData(const std::string& filename);
        virtual UserBuilder getUserBuilder(const std::string& functionName) const;

        struct UserBuilder
       {
        UserBuilder(std::string functionName) : m_functionName{functionName} {};
        virtual ~UserBuilder();
        virtual UserBuilder& fun1();
        virtual UserBuilder& fun2(int32_t num);
        virtual bool callFunction();
       private:
        std::string m_functionName{};
      };
}

这是用户的模拟类:

class UserMock : public User
{
public:
    MOCK_METHOD1(loadData, int(const std::string& filename));
    MOCK_CONST_METHOD1(getUserBuilder, UserBuilder(const std::string& functionName));
};

Thsi是UserBuilder的模拟类:

struct UserBuilderMock : public User::UserBuilder
{
public:
    UserBuilderMock(std::string functionName) : User::UserBuilder(functionName) {}
    MOCK_METHOD0(fun1, UserBuilder&());
    MOCK_METHOD1(fun2, UserBuilder&(int32_t num));
    MOCK_METHOD0(callFunction, bool());
};

我要测试此功能:

void useCase(std::unique_ptr<User> userP)
{   
    int status = userP->loadFile("init");
    if (status == 0)
    {
        User::UserBuilder builder = userP->getUserlBuilder("init");
        bool result = builder.fun1().fun2(1).callFunction();
        return result;
    }
    else
    {
        return false;
    }
}

我给getUserBuilder(“ init”)一个模拟对象builderMock作为其返回值,如下所示:

auto userMock = std::make_unique<UserMock>();
ON_CALL(*userMock, loadFile("init")).WillByDefault(Return(0));
UserBuilderMock builderMock("init");
EXPECT_CALL(*userMock, getUserBuilder("init")).WillOnce(ReturnPointee(&builderMock));
EXPECT_CALL(builderMock,fun1()).Times(1);

测试日志失败:fun1从未调用过且未激活。 我想使用builderMock对象来调用模拟方法fun1,fun2和callFunction,但它仍使用真实的UserBuilder对象 调用真正的fun1,fun2和callFunction。我应该怎么做才能使它使用Mock对象调用Mock方法?

1 个答案:

答案 0 :(得分:0)

您必须重写代码,以使User :: getUserBuilder返回指向UserBuilder的指针(可能是一个聪明的指针)。

使用方法返回UserBuilder对象

EXPECT_CALL(*userMock, getUserBuilder("init")).WillOnce(ReturnPointee(&builderMock));

getUserBuilder将模拟对象转换为其基类的对象(切片),而失去所有模拟对象的添加。