代码之家  ›  专栏  ›  技术社区  ›  Joe

为单元测试更改类功能的正确方法?

  •  -1
  • Joe  · 技术社区  · 6 年前

    我正在研究一个古老的C++ C++代码库,我一直在为缺少它们的组件创建单元测试的过程。

    为了测试,模仿这些类的功能的正确方法是什么?目前我使用的是虚拟函数,在我的测试模块中,我从基本的“生产”类派生一个模拟类,并根据需要重写功能。

    举个例子:

    生产.cpp

    class Production {
    protected:
        int Servers = 0;
    public:
    
        virtual bool IsValInRegistry(const std::string& regVal);
    };
    
    bool Production::IsValInRegistry(const std::string& regVal)
    {
        HRESULT hr = GOOD;
        hr = WinSysCallToRegistry(regVal);
    
        if (HR)
            return true;
        else
            return false;
    }
    

    class Mock : public Production {
    public:
        bool IsValInRegistry(const std::string& regVal) override final;
    };
    
    Mock::IsValInRegistry(const std::string& regVal)
    {
        return true;
    }
    

    这是正确的方法吗?我担心我介绍的人太多了 virtual 功能,我可能会看到一个性能冲击,我想避免。如果这个 virutal

    1 回复  |  直到 6 年前
        1
  •  0
  •   Kirill Voroshilov    6 年前

    class Production {
    protected:
        int Servers = 0;
    public:
    
        bool IsValInRegistry(const std::string& regVal);
    };
    
    bool Production::IsValInRegistry(const std::string& regVal)
    {
    #ifdef USE_MOCK_PRODUCTION
        return true;
    #else
        HRESULT hr = GOOD;
        hr = WinSysCallToRegistry(regVal);
    
        if (HR)
            return true;
        else
            return false;
    #endif
    }