我之前用另一个名字问过这个问题,但因为我没有很好地解释它而删除了它。
假设我有一个管理文件的类。假设此类将文件视为具有特定文件格式,并包含对该文件执行操作的方法:
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/