我正在为我的c ++项目编写单元测试,其中有许多调用glibc函数的函数(malloc,读取,打开,写入,关闭等),还有一些外部库函数,例如openssl(SHA256函数)。
例如,Follow函数计算给定文件的SHA256校验和。现在,此函数对标准/外部库函数(例如fopen,SHA256_Init,malloc等)进行了多次调用。现在,如何对这些函数进行调用存根(作为我们的主要目标)是单元测试SHA256file,而不是其调用的函数。
int MyClass::SHA256File(const char *path,char outputBuffer[65])
{
FILE *file = fopen(path,"rb");
if(!file) {
throw exception("Failed to open file for SHA256 computation.");
}
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
if ( !SHA256_Init(&sha256) ) {
throw exception("SHA256_Init failed.");
}
const int bufSize = 32768;
unsigned char *buffer = (unsigned char*) malloc(bufSize);
int bytesRead = 0;
if(!buffer) {
throw exception("Failed to allocate buffer for SHA256 computation.");
}
while( fgets((char*)buffer,bufSize,file) != NULL ) {
curr_pos = ftell(file);
bytesRead = curr_pos - last_pos;
last_pos = curr_pos;
if( !SHA256_Update(&sha256,buffer,bytesRead) ) {
throw exception("SHA256_Update failed..");
}
}
if ( ferror(file) ) {
throw exception("Failed to read file for SHA256 computation.");
}
if( !SHA256_Final(hash,&sha256) ) {
throw exception("SHA256_Final failed..");
}
int i = 0;
for(i = 0; i < SHA256_DIGEST_LENGTH; i++) {
sprintf(outputBuffer + (i * 2),"%02x",hash[i]);
}
outputBuffer[64] = 0;
fclose(file);
free(buffer);
return 0;
}
我没有像glibcmock这样的指针,但是如果glibc / gmock可以提供,我希望有一些标准的支持。
谢谢。