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

标签 c++ unit-testing refactoring

这个问题来自一个真实世界的项目,它经常使用“在基类中提供 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/

相关文章:

c++ - 如何生成具有指数分布(均值)的随机数?

php - 验证 Symfony 4 单元测试中的命令独白输出

unit-testing - Swift、访问修饰符和单元测试

java - 任何工具都可以帮助将字段重构为 get/set 方法对

android - 如何在 Eclipse 中格式化 Android xml?

c++ - C++:从std::list删除指针

c++ - NULL 与抛出和性能

c++ - 我想在 C++ 中查看 hash_map 示例

php - 模拟静态 Eloquent 模型方法,包括 find()

go - 如何避免路由器处理代码中的代码重复