如何使用运算符[]创建模拟类

How to create a mock class with operator[]?

本文关键字:创建 模拟类 何使用 运算符      更新时间:2023-10-16

我有一个operator[]类,如下所示:

class Base
{
  public:
    virtual ~Base(){}
    virtual const int & operator[]( const unsigned int index ) const = 0;
};

如何使用google mock框架为该方法创建mock类?

我试过这个:

class MockBase : public Base
{
public:
  MOCK_CONST_METHOD1( operator[],
                      const int& ( const unsigned int )
                      );
};

但这会产生下一个错误:

error: pasting "]" and "_" does not give a valid preprocessing token
error: pasting "]" and "_" does not give a valid preprocessing token
error: pasting "]" and "_" does not give a valid preprocessing token
error: pasting "]" and "_" does not give a valid preprocessing token

MOCK_METHOD#宏无法在运算符上工作。这个消息中给出的解决方案说要创建一个常规的模拟方法:

class Base {
 public:
 virtual ~Base () {}
 virtual bool operator==(const Base &) = 0;
};
class MockBase: public Base {
 public:
 MOCK_METHOD1(Equals, bool(const Base &));
 virtual bool operator==(const Base & rhs) { return Equals(rhs); }
};