Google Mock: Return() a list of values

为君一笑 提交于 2020-01-03 15:34:24

问题


Via Google Mock's Return() you can return what value will be returned once a mocked function is called. However, if a certain function is expected to be called many times, and each time you would like it to return a different predefined value.

For example:

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

How do you make aCertainFunction each time return an incrementing integer?


回答1:


Use sequences:

using ::testing::Sequence;

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



回答2:


Use functors, as explained here.


Something like this :

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:


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


来源:https://stackoverflow.com/questions/5144623/google-mock-return-a-list-of-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!