c++ - 如何使用谷歌模拟模拟宏功能

标签 c++ c googlemock

我需要模拟在 linux 头文件中定义的宏:

#include <asm/types.h>
#include <linux/netlink.h>

for (msg_ptr = (struct nlmsghdr *) reply; 
     NLMSG_OK(msg_ptr, len); 
     msg_ptr = NLMSG_NEXT(msg_ptr, len))
{
   // do something
}

NLMSG_OK 在一些 linux 头文件 linux/netlink.h 中定义。

如何使用 google mock 模拟它?

google mock 是否支持模拟宏?

最佳答案

How to mock it using google mock?

你不能。

Does google mock support mocking macro?

没有。

首先,宏不是函数!它们只是从预处理阶段扩展而来的文本处理模板。

好吧,我们假设宏以某种方式扩展为全局函数调用,他们在 FAQ 中给出了以下答案:

My code calls a static/global function. Can I mock it?

You can, but you need to make some changes.

In general, if you find yourself needing to mock a static function, it's a sign that your modules are too tightly coupled (and less flexible, less reusable, less testable, etc). You are probably better off defining a small interface and call the function through that interface, which then can be easily mocked. It's a bit of work initially, but usually pays for itself quickly.

This Google Testing Blog post says it excellently. Check it out


关于您的评论“您使用#undef 和重新#define 是什么意思?”:

我的意思是您需要使用自己的宏定义来编译被测代码,这会注入(inject)一个 Google Mock 类/函数。

#if defined(UNDER_TEST)
#undef NLMSG_OK
#define NLMSG_OK(msg_ptr, len) \
     // your mocking code
#endif

关于c++ - 如何使用谷歌模拟模拟宏功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33149466/

相关文章:

c++ - 尾随返回类型中的名称查找问题

c++ - 在 C++ 中复制多维数组引用

c++ - 零大小结构

c - 如何使用 SetMenuInfo,更改菜单栏的文本

c++ - 将在抽象基类上定义的 vector 的元素与具体的派生类进行匹配

c++ - Google 测试框架不打印 std::optional

c++ - googlemock 可以从同一类的其他方法调用中模拟方法调用吗?

c++ - 如何将函数模板作为(模板)参数传递给函数模板?

c++ - 如何从另一个平台(iOS 到 Windows)打开和读取 SQLite 数据库

c - 通过引用错误传递结构(不完整的结构和重新声明)