c++ - 单元测试资源管理类中的私有(private)方法 (C++)

标签 c++ unit-testing raii boost-test

我之前用另一个名字问过这个问题,但因为我没有很好地解释它而删除了它。

假设我有一个管理文件的类。假设此类将文件视为具有特定文件格式,并包含对该文件执行操作的方法:

class Foo {
    std::wstring fileName_;
public:
    Foo(const std::wstring& fileName) : fileName_(fileName)
    {
        //Construct a Foo here.
    };
    int getChecksum()
    {
        //Open the file and read some part of it

        //Long method to figure out what checksum it is.

        //Return the checksum.
    }
};

假设我希望能够对此类中计算校验和的部分进行单元测试。对加载到文件中的类部分进行单元测试是不切实际的,因为要测试 getChecksum() 方法的每个部分,我可能需要构建 40 或 50 个文件!

现在假设我想在类(class)的其他地方重用校验和方法。我提取该方法,使其现在看起来像这样:

class Foo {
    std::wstring fileName_;
    static int calculateChecksum(const std::vector<unsigned char> &fileBytes)
    {
        //Long method to figure out what checksum it is.
    }
public:
    Foo(const std::wstring& fileName) : fileName_(fileName)
    {
        //Construct a Foo here.
    };
    int getChecksum()
    {
        //Open the file and read some part of it

        return calculateChecksum( something );
    }
    void modifyThisFileSomehow()
    {
        //Perform modification

        int newChecksum = calculateChecksum( something );

        //Apply the newChecksum to the file
    }
};

现在我想对 calculateChecksum() 方法进行单元测试,因为它易于测试且复杂,我不关心单元测试 getChecksum()因为它很简单而且很难测试。但我无法直接测试 calculateChecksum(),因为它是 private

有谁知道这个问题的解决方案吗?

最佳答案

一种方法是将校验和方法提取到它自己的类中,并有一个用于测试的公共(public)接口(interface)。

关于c++ - 单元测试资源管理类中的私有(private)方法 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2253950/

相关文章:

c++ - SHFILEOPSTRUCT 不确定如何加倍转义字符串

c++ - C++ 中的简单数组使用?

java - 单元测试重载方法

c++ - 何时不使用 RAII 进行资源管理

c++ - 我们可以像在命名空间中那样为类名取别名吗?

c++ - "control reaches end of non-void function"枚举类型完全处理大小写切换

unit-testing - 我可以使Intellij Idea 11 IDE意识到Grails 2.0.x单元测试中的assertEquals和其他JUnit方法吗?

php - 没有依赖注入(inject)的方法的模拟对象

c++ - 如果我忽略具有 shared_ptr 返回类型的函数的返回值怎么办

c++ - 除了 C++ 之外,其他语言的程序员是否使用、了解或理解 RAII?