gpt4 book ai didi

c++ - 重构 protected 基类依赖以进行测试

转载 作者:行者123 更新时间:2023-11-30 05:20:49 25 4
gpt4 key购买 nike

这个问题来自一个真实世界的项目,它经常使用“在基类中提供 protected 接口(interface)”模式。

这是一个小例子:

class UntouchableBase
{
protected: //cannot be called from outer class
int GetValue() { return 42;}//not virtual

//this class has many many more "protected interface" methods
};

class HeavyWeightClassIWantToTest: public UntouchableBase
{
public:
// VeryHeavyClassIWantToTest(...) {} //ignore the creation issue for a heavy weight object here

void MethodThatNeedsTest()
{
//calc some values
int result = GetValue();
//do some other stuff
}
};

我正在寻找一种快速的、主要是非侵入性的重构来替换 GetValue 依赖项。HeavyWeightClassIWantToTest

允许提取方法和添加新类

@UPDATE:测试,说明问题

TEST(EnsureThat_MyMethodThatNeedsTestDoesSthSpecial)
{
HeavyWeightClassIWantToTest sut = MakeSut();

sut.MethodThatNeedsTest(); //should call a mocked / replaced GetValue()
}

提示:目前我们正在使用链接接缝替换 UntouchableBase 实现以进行测试。

请提供编码示例。

最佳答案

你有模板方式:

template <typename Base>
class HeavyWeightClassIWantToTestGeneric: public Base
{
public:
// ...

void MethodThatNeedsTest()
{
//calc some values
int result = this->GetValue(); // use `this->` for dependent name
//do some other stuff
}
};

// For production
using HeavyWeightClassProduction = HeavyWeightClassIWantToTestGeneric<UntouchableBase>;

// For Test
using HeavyWeightTest = HeavyWeightClassIWantToTestGeneric<TestBase>;

关于c++ - 重构 protected 基类依赖以进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40502514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com