Google Mock: Return () list of values

Through Google Mock Return (), you can return what value will be returned after calling the mocked function. However, if it is expected that a particular function will be called many times, and every time you want it to return another predetermined value.

For instance:

EXPECT_CALL(mocked_object, aCertainFunction (_,_)) .Times(200); 

How do you do aCertainFunction every time returning an incrementing integer?

+4
source share
3 answers

Use sequences :

 using ::testing::Sequence; Sequence s1; for (int i=1; i<=20; i++) { EXPECT_CALL(mocked_object, aCertainFunction (_,_)) .InSequence(s1) .WillOnce(Return(i)); } 
+5
source

Use functors as described here .


Something like that:

 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 ); 
+3
source

You might like this solution, which hides implementation details in the mock class.

In the mock class add:

 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; } 

In the test, call:

 TEST_F(TestSuite, TestScenario) { MockObject mocked_object; mocked_object.useAutoIncrement(0); // the rest of the test scenario ... } 
0
source

Source: https://habr.com/ru/post/1341675/


All Articles