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