使用gmock模拟标准库函数

问题描述 投票:0回答:1

以下是我要进行单元测试的功能:

void sampleFunc()
{
   FILE *file = fopen(path, "rb");
   if(!file) {
     cout<<"File couldn't be opened!"<<endl;
   }
   const int bufSize = 32768;                                              
   unsigned char *buffer = (unsigned char*) malloc(bufSize);               

   if(!buffer) {                                                           
     fclose(file);                                                       
     std::cout<<"Failed to allocate buffer for SHA256 computation."<<endl;
   }
   ..
   // Read file into buffer
   ..
}

如代码中所示,我的函数使用许多标准库函数。我应该嘲笑吗标准库函数还是对函数进行实际调用?

感谢您的任何帮助。

提前感谢。

c++ googletest googlemock
1个回答
0
投票

您可以做什么来测试您的功能:

class IFileManager
{
public:
    virtual ~IFileManager() = default;

    // You could even improve interface by returning RAII object
    virtual FILE* fopen(const char* path, const char* mode) = 0;
    virtual void fclose(FILE*) = 0;
    // ...
};

class FileManager : public IFileManager
{
public:
    FILE* fopen(const char* path, const char* mode) override { return ::fopen(path, mode); }
    int fclose(FILE* f) override { return ::fclose(f); }
    // ...
};

class IAllocator
{
public:
    virtual ~IAllocator() = default;

    virtual void* allocate(std::size_t) = 0;
    virtual void deallocate(void*) = 0;
};

class Allocator : public IAllocator
{
public:
    void* allocate(std::size_t size) override { return malloc(size); }
    void deallocate(void* p) override { free(p); }
};

您的功能将变为:

void sampleFunc(IFileManager& fileManager, IAllocator& allocator)
{
   FILE *file = fileManager.fopen(path, "rb");
   if(!file) {
     std::cout << "File couldn't be opened!" << endl;
     return;
   }
   const int bufSize = 32768;
   unsigned char *buffer = (unsigned char*) allocator.allocate(bufSize);

   if(!buffer) {
     fileManager.fclose(file);
     std::cout << "Failed to allocate buffer for SHA256 computation." << std::endl;
     return;
   }
   // Read file into buffer
   // ...
}

最后,您可以轻松模拟IFileManagerIAllocator

没有该接口,您将必须使标准函数按预期方式运行,这不一定是简单可行的(错误的路径,限制的内存(限制))

还请注意,实施可能会有更多限制。从接口(MAX_PATH,非常规文件,UNC路径)获取的那个]

© www.soinside.com 2019 - 2024. All rights reserved.