How to use gmock MOCK_METHOD for overloaded operators?

耗尽温柔 提交于 2020-07-20 07:26:22

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/43796479/how-to-use-gmock-mock-method-for-overloaded-operators

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