提问者:小点点

为unittest调用继承类的私有成员


我在写一个unittest,但是遇到了一些问题。

我有一个类,它有一个int来跟踪当前状态。继承此类的所有类都可以通过调用ProtectedFunction来更改状态。

class RandomClass
{
public:
  RandomClass()
  { 
    mState = 0; 
  }
protected:
  void protectedFunction()
  {
    ++mState;
  }
private:
  int mState;
  friend void UNITTEST_setMState(int state);
  friend int UNITTEST_getMState();
};

现在我想为这个类编写一个unittest。所以我创建了一个新的类,它继承了以前的类。为了正确测试所有的状态,我需要设置状态,并且我需要获得状态来断言它。我试过使用一个朋友功能,但它似乎不起作用。

class UnittestRandomClass : public RandomClass
{
public:
  void wrapperProtectedFunction()
  {
    protectedFunction();
  }

  void UNITTEST_setMState(int state)
  {
    this->mState = state; // Apparently not like this
  }

  int UNITTEST_getMState()
  {
    return this->mState; // Apparently not like this
  }
};

int main() {
  UnittestRandomClass ut;
  ut.UNITTEST_setMState(1);
  ut.wrapperProtectedFunction();
  int res = ut.UNITTEST_getMState();
  ASSERT_EQ(res, 2);
}

我似乎做错了什么,因为mState看起来仍然是私有的,因此我得到了一个无法访问的错误。我也尝试通过返回mState直接调用它,但是同样的错误仍然适用。

一个解决方案是将mState移动到protected,但是由于还有其他类继承了RandomClass,我不认为这是一个节省的解决方案。

那么我如何才能解决这样的问题和解决我的错误呢?


共1个答案

匿名用户

您的类将一个独立函数声明为Friend。

您的单元测试使用一个类的成员函数,这个类没有声明为Friend。

您可以编写友类UnitTestRandomClass;