问题描述
我尝试模拟User类及其嵌套结构UserBuilder:
I try to mock a User class and its nested struct 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的模拟类:
Thsi is the mock class for 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作为其返回值,如下所示:
I give the getUserBuilder("init") a mock object builderMock as its return value, like this:
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方法?
The test log fail: fun1 never called-unsatisfied and active.I want to use the builderMock object to call the mock method fun1,fun2 and callFunction, but it still use the real UserBuilder objectcall the real fun1,fun2 and callFunction. What should I do to make it use Mock object call the Mock method?
推荐答案
您必须重写代码以使User :: getUserBuilder返回指向UserBuilder的指针(可能是聪明的指针).
You have to rewrite your code to make User::getUserBuilder return a pointer (possibly smart one) to UserBuilder.
使用方法返回UserBuilder对象
With the method returning UserBuilder object
EXPECT_CALL(*userMock, getUserBuilder("init")).WillOnce(ReturnPointee(&builderMock));
getUserBuilder将模拟对象转换为其基类的对象(切片),而失去所有模拟对象的添加.
getUserBuilder casts the mock to an object of its base class (slicing), losing all the the mock additions.
这篇关于如何模拟返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!