如何在C 中更改静态方法行为

How can I change a static method behavior in C++?

本文关键字:静态方法      更新时间:2023-10-16

是否有一种方法可以修改静态方法的行为以返回不同的参数?

我正在使用gmock进行模拟,但在这种情况下,我无法更改我的代码,方法必须保持静态

例如

class MyClass
{
public:
    static int GetSomething()
    {
        return -1; 
    }
};

我需要返回正数的方法

在这种情况下,您的选项有限,但是如果仅是一个模拟,则只需使该方法返回静态变量而不是硬编码值即可。

class MyClass
{
  static int somethingValue;
public:
  static int GetSomething()
  {
    return somethingValue; 
  }
  static void SetSomething(int value)
  {
    somethingValue = value; 
  }
};
int MyClass::somethingValue = -1;

免责声明 - 我在单位测试公司打字。您可以通过我们的API轻松更改方法的行为,例如:

WHEN_CALLED(MyClass::GetSomething()).Return(15);

这样,在您的所有测试中,GetSomehting都将返回15。它也将用于非静态方法。