首页 > 解决方案 > 是否可以在不使用 gmock 修改源代码的情况下模拟系统调用(例如:malloc)?

问题描述

我想模拟诸如 malloc/file-open 之类的系统调用,以便在不修改生产代码的情况下对我的代码进行单元测试。此外,在源代码中为这些系统调用创建包装器是不可行的,因此该选项被排除在外。

任何输入/解决方案都会有所帮助。

标签: unit-testingmallocsystem-callsgoogletestgooglemock

解决方案


模拟系统调用是有问题的,因为 gtest 和 gmock 本身也可能使用相同的函数。而且,由于将它们包装在源代码中也不是一种选择,因此可能没有太多可能性了。

您可以尝试的一件事是在编译源代码文件时使用预处理器替换这些调用。它不符合标准,但通常可以工作。假设您需要测试的代码在 file 中foo.cpp。该文件foo.cpp包括a.handb.h和, for malloc, <cstdlib>.

你想要做的是#define malloc malloc_mock,但要让它工作(至少有可能 - 正如我所说的那样,这是一个不合规的黑客),你必须在你的文件中以下列方式进行foo_test.cpp

#include <a.h>      // before malloc is re-defined
#include <b.h>      // also before re-defining malloc
#include <cstdlib>  // and again
// Now all files are included that foo.cpp also includes.
// Let's hope every file has an include-guard in place ...

void* malloc_mock (size_t size);

#define malloc malloc_mock
// now, in the code of foo.cpp, all calls to malloc are substituted:
#include "foo.cpp" // include guards protect a.h etc. from being affected 
#undef malloc

... your tests come here

丑陋?当然。但是,限制来自你,所以不要要求美丽的东西。

附带说明:在模拟的特殊情况下,malloc我假设您正在尝试实现一些内存泄漏检查 - 如果是这样,我建议不要模拟它,而是在 valgrind 下运行您的单元测试......


推荐阅读