Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use gmock MOCK_METHOD for overloaded operators?

I am new to googlemock (and StackOverflow). I got a problem when using MOCK_METHODn in googlemock and I believe this function is widely used. Here is what I did.

I have an abstract class Foo with virtual overloaded operator[]:

class Foo{
public:
      virtual ~Foo(){};
      virtual int operator [] (int index) = 0;
}

and I want to use googlemock to get a MockFoo:

class MockFoo: public Foo{
public:
      MOCK_METHOD1(operator[], int(int index));  //The compiler indicates this line is incorrect
}

However, this code gives me a compile error like this:

error: pasting "]" and "_" does not give a valid preprocessing token
  MOCK_METHOD1(operator[], GeneInterface&(int index));

My understanding is that compiler misunderstands the operator[] and doesn't take it as a method name. But what is the correct way to mock the operator[] by using MOCK_METHODn? I have read the docs from googlemock but found nothing related to my question. Cound anyone help me with it?

Thanks!

like image 564
Ruoxi Avatar asked May 05 '17 04:05

Ruoxi


People also ask

What is Gmock in Gtest?

Gtest is a framework for unit testing. Gmock is a framework imitating the rest of your system during unit tests.

What is Expect_call Gtest?

EXPECT_CALL not only defines the behavior, but also sets an expectation that the method will be called with the given arguments, for the given number of times (and in the given order when you specify the order too).

What is Mock_method?

You must always put a mock method definition ( MOCK_METHOD ) in a public: section of the mock class, regardless of the method being mocked being public , protected , or private in the base class.


1 Answers

You can't. See: https://groups.google.com/forum/#!topic/googlemock/O-5cTVVtswE

The solution is to just create a regular old fashioned overloaded method like so:

class Foo {
 public:
 virtual ~Foo() {}
 virtual int operator [] (int index) = 0;
};

class MockFoo: public Foo {
 public:
 MOCK_METHOD1(BracketOp, int(int index));
 virtual int operator [] (int index) override { return BracketOp(index); }
}; 
like image 190
ifma Avatar answered Oct 13 '22 20:10

ifma