我需要模拟在 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/