C++ googlemock:Return()值的列表
通过googlemock的Return()可以返回调用模拟函数后将返回的值。但是,如果某个函数需要多次调用,并且每次都希望它返回不同的预定义值 例如:C++ googlemock:Return()值的列表,c++,return-value,googlemock,C++,Return Value,Googlemock,通过googlemock的Return()可以返回调用模拟函数后将返回的值。但是,如果某个函数需要多次调用,并且每次都希望它返回不同的预定义值 例如: EXPECT_CALL(mocked_object, aCertainFunction (_,_)) .Times(200); 如何使aCertainFunction每次返回递增整数?使用: 使用::testing::Sequence; 序列s1; 对于(int i=1;i使用函子,如上所述 大概是这样的: int aCertainF
EXPECT_CALL(mocked_object, aCertainFunction (_,_))
.Times(200);
如何使aCertainFunction每次返回递增整数?使用:
使用::testing::Sequence;
序列s1;
对于(int i=1;i使用函子,如上所述
大概是这样的:
int aCertainFunction( float, int );
struct Funct
{
Funct() : i(0){}
int mockFunc( float, int )
{
return i++;
}
int i;
};
// in the test
Funct functor;
EXPECT_CALL(mocked_object, aCertainFunction (_,_))
.WillRepeatedly( Invoke( &functor, &Funct::mockFunc ) )
.Times( 200 );
您可能喜欢此解决方案,它在模拟类中隐藏了实现细节
在模拟类中,添加:
using testing::_;
using testing::Return;
ACTION_P(IncrementAndReturnPointee, p) { return (*p)++; }
class MockObject: public Object {
public:
MOCK_METHOD(...)
...
void useAutoIncrement(int initial_ret_value) {
ret_value = initial_ret_value - 1;
ON_CALL(*this, aCertainFunction (_,_))
.WillByDefault(IncrementAndReturnPointee(&ret_value));
}
private:
ret_value;
}
在测试中,调用:
TEST_F(TestSuite, TestScenario) {
MockObject mocked_object;
mocked_object.useAutoIncrement(0);
// the rest of the test scenario
...
}
TEST_F(TestSuite, TestScenario) {
MockObject mocked_object;
mocked_object.useAutoIncrement(0);
// the rest of the test scenario
...
}