googlemock可以从同一个类的其他方法调用中模拟方法调用吗? [英] Can googlemock mock method calls from within other method calls of the same class?
问题描述
是否可以从同一类的其他方法调用中模拟方法调用?我是C ++的新手(主要是C开发人员),并且是googlemock和Google Test的新手,所以请原谅我,如果我在其他地方回答了这个问题,但我听不懂答案!下面是一个简单的示例,应该解释我想要做什么.使用下面的示例,我想在测试ReturnInputPlus1
时模拟ReturnInput
.
Is it possible to mock method calls from within other method calls of the same class? I am new to C++ (primarily a C developer) and very new to googlemock and Google Test so forgive me if this is answered elsewhere and I didn't understand the answer! Below is a simple example that should explain what I want to do. Using the example below, I want to mock ReturnInput
, while testing ReturnInputPlus1
.
using ::testing::Invoke;
using ::testing::_;
using ::testing::Return;
class MyClass
{
public:
MyClass() : x(1) {}
virtual ~MyClass() {}
int ReturnInput(int x) { return x; }
int ReturnInputPlus1(int x) { return ReturnInput(x) + 1; }
};
class MockMyClass : public MyClass
{
public:
MockMyClass()
{
ON_CALL(*this, ReturnInput(_)).WillByDefault(Invoke(&real, &MyClass::ReturnInput));
ON_CALL(*this, ReturnInputPlus1(_)).WillByDefault(Invoke(&real, &MyClass::ReturnInputPlus1));
}
virtual ~MockMyClass() {}
MOCK_METHOD1(ReturnInput, int(int y));
MOCK_METHOD1(ReturnInputPlus1, int(int));
private:
MyClass real;
};
TEST(MyClassTest, mockUseClassMethod)
{
MockMyClass mock;
EXPECT_CALL(mock, ReturnInput(_))
.WillOnce(Return(2));
EXPECT_CALL(mock, ReturnInputPlus1(_))
.Times(1);
EXPECT_EQ(3, mock.ReturnInputPlus1(1));
}
运行上述测试时,我希望所有测试都能成功.相反,我得到以下输出:
When I run the above test, I would expect all the tests to succeed. Instead I get the following output:
1>[ RUN ] MyClassTest.mockUseClassMethod
1>.\MyClassTest.cpp(15): error: Value of: mock.ReturnInputPlus1(1)
1> Actual: 2
1>Expected: 3
1>.\DllInfoTest.cpp(10): error: Actual function call count doesn't match EXPECT_CALL(mock, ReturnInput(_))...
1> Expected: to be called once
1> Actual: never called - unsatisfied and active
推荐答案
默认情况下,您对MockMyClass::ReturnInputPlus1(1)
的调用会调用real
上的MyClass::ReturnInputPlus1(1)
,该调用会调用MyClass::ReturnInput(2)
.运行ReturnInputPlus1()
的对象不是mock
,而是mock.real
,并且在调用ReturnInput()
时会调用该函数的原始版本.您想要做的是创建一个具有ReturnInput()
的模拟替代但完全不模拟ReturnInputPlus1()
的MockMyClass -您既不想同时拥有该类的模拟版本,又不想拥有一个有时委派给.
Your call to MockMyClass::ReturnInputPlus1(1)
calls MyClass::ReturnInputPlus1(1)
on real
by default, which calls MyClass::ReturnInput(2)
. The object that ReturnInputPlus1()
is running on is not mock
, it's mock.real
, and when it calls ReturnInput()
it calls the original version of the function. What you want to do is create a MockMyClass that has a mock override of ReturnInput()
but doesn't mock out ReturnInputPlus1()
at all -- you don't want to have both a mock version of your class and a real version that it sometimes delegates to.
这篇关于googlemock可以从同一个类的其他方法调用中模拟方法调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!