[英]C++ GoogleMock mock method call within another method of the same class
I was looking at this question here: Can googlemock mock method calls from within other method calls of the same class?我在这里看这个问题: Can googlemock mock method calls from within other method call of the same class?
and tried to implement the answer, however it does not work for me.并试图实施答案,但它对我不起作用。
I have modified the link question implementation to remove the mock ReturnInputPlus1()
which is what the accepted answer suggests:我已经修改了链接问题实现以删除模拟
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; }
private:
int x;
};
class MockMyClass : public MyClass
{
public:
MockMyClass()
{
ON_CALL(*this, ReturnInput(_)).WillByDefault(Invoke(&real, &MyClass::ReturnInput));
}
virtual ~MockMyClass() {}
MOCK_METHOD1(ReturnInput, int(int y));
private:
MyClass real;
};
TEST(MyClassTest, mockUseClassMethod)
{
MockMyClass mock;
EXPECT_CALL(mock, ReturnInput(_))
.WillOnce(Return(2));
EXPECT_EQ(3, mock.ReturnInputPlus1(1));
}
This still returns the same failure这仍然返回相同的失败
/projects/tests/cpp/google-test/test.cpp:46: Failure
Expected: 3
To be equal to: mock.ReturnInputPlus1(1)
Which is: 2
/projects/tests/cpp/google-test/test.cpp:41: Failure
Actual function call count doesn't match EXPECT_CALL(mock, ReturnInput(_))...
Expected: to be called once
Actual: never called - unsatisfied and active
I do not see a way to achieve the redirection of the internal call to the mock behaviour without making the methods in MyClass virtual .我没有看到一种方法可以在不使 MyClass 中的方法成为virtual 的情况下实现将内部调用重定向到模拟行为。
Below is a working example:下面是一个工作示例:
real
member, the mock is inheriting MyClass anywayreal
成员,无论如何模拟都继承了 MyClassmock.MyClass::ReturnInputPlus1(1)
( qualified name lookup ) and to understand that dynamic dispatch will cause the usage of MockMyClass::ReturnInput.mock.MyClass::ReturnInputPlus1(1)
(限定名称查找)并了解动态调度将导致使用 MockMyClass::ReturnInput。class MyClass
{
public:
MyClass()
: m_x(1)
{
}
virtual ~MyClass() {}
virtual int ReturnInput(int x) { return x; }
virtual int ReturnInputPlus1(int x) { return ReturnInput(x) + 1; }
private:
int m_x;
};
class MockMyClass : public MyClass
{
public:
MockMyClass()
: MyClass()
{
ON_CALL(*this, ReturnInput(_)).WillByDefault(Invoke(this, &MyClass::ReturnInput));
}
virtual ~MockMyClass() {}
MOCK_METHOD1(ReturnInput, int(int y));
MOCK_METHOD1(ReturnInputPlus1, int(int y));
};
TEST(MyClassTest, mockUseClassMethod)
{
MockMyClass mock;
EXPECT_CALL(mock, ReturnInput(_)).WillOnce(Return(2));
EXPECT_EQ(3, mock.MyClass::ReturnInputPlus1(1));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.