code3
code3

Reputation: 91

Google mock invoke function with parameters

static bool helper(int a){
   // do something here
   return true;
}  

  class ProxyMock : public Proxy
    {
        public:
            MOCK_METHOD1(functionA, bool(
                int a
            ));
    };


TEST(xxx, xxx){
   ProxyMock mock;
   int a;
   EXPECT_CALL(mock, functionA(5)).WillOnce(testing::Invoke(helper(a));  
}

when functionA of mock object is called with parameter(5), I would like to invoke a static global function helper which takes in the parameter I want. When compiling I got errors: 'function' cannot be used as a function in the EXPECT_CALL line. What is wrong?

Upvotes: 3

Views: 5489

Answers (2)

Ari
Ari

Reputation: 7556

You can directly pass a callable of zero args that somehow has access to a to WillOnce. The easiest way to do so is using a lambda:

EXPECT_CALL(mock, functionA(5))
  .WillOnce([a]() { return helper(a); });

Note that Invoke passes the same argument that was passed to the function under test. So you should use it only if you want to pass 5 to helper:

EXPECT_CALL(mock, functionA(5))
   .WillOnce(testing::Invoke(helper));  // helper(5) will be called.

As an alternative you can use InvokeWithoutArgs, which acts like Invoke but does not pass any arguments to the callable that is its argument, but then again you should use something like a lambda capture to get access to a, so it's not necessary.

Live example: https://godbolt.org/z/vqdxT86E4

Upvotes: 1

Yksisarvinen
Yksisarvinen

Reputation: 22176

Invoke requires a functor. Functor is something that can be called (using operator()), e.g. a function pointer, a struct with overloaded operator() or a lambda.
Moreover, it requires the functor to match the mocked function regarding parameter types and return type (your helper fits that criteria), and it will always pass the arguments that mocked function received into that functor (which you don't want).

If you want to call a function with different argument, the simplest way would be to use InvokeWithoutArgs and a lambda:

   EXPECT_CALL(mock, functionA(5)).WillOnce(
        testing::InvokeWithoutArgs(
            [a](){return helper(a);}
        )
    );  

See it online

Upvotes: 3

Related Questions