unit-testing - 是否可以在不使用 gmock 修改源代码的情况下模拟系统调用(例如:malloc)?
问题描述
我想模拟诸如 malloc/file-open 之类的系统调用,以便在不修改生产代码的情况下对我的代码进行单元测试。此外,在源代码中为这些系统调用创建包装器是不可行的,因此该选项被排除在外。
任何输入/解决方案都会有所帮助。
解决方案
模拟系统调用是有问题的,因为 gtest 和 gmock 本身也可能使用相同的函数。而且,由于将它们包装在源代码中也不是一种选择,因此可能没有太多可能性了。
您可以尝试的一件事是在编译源代码文件时使用预处理器替换这些调用。它不符合标准,但通常可以工作。假设您需要测试的代码在 file 中foo.cpp
。该文件foo.cpp
包括a.h
andb.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 下运行您的单元测试......
推荐阅读
- sql - 为什么 SQL 中外连接的结果包含 null 列,而原始表没有?
- ruby-on-rails - RSpec/Capybara:设置一个经常调用的例程
- matlab - 使用 Matlab FFT 计算的频谱对于不同长度的样本(点数相同但 Fs 不同)给出的结果不一致?
- c# - 过程或函数收入指定了太多参数
- hive - 带反引号的选择子句
- scala - Hadoop 端口:fs.default.name
- bootstrap-4 - Bootstrap Vue 的垂直间距
- html - 当浏览器窗口大小基于纯 css 发生变化时,在 span 中显示点
- c - M_PI 不精确
- csv - 为 Conv 神经网络解析 CSV 形式的修改后的 MNIST