开发者

Google Mock: Return() a list of values

Via Go开发者_如何学编程ogle 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?


Use sequences:

using ::testing::Sequence;

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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜