如何使用 google mock 模拟宏函数
how to mock macro function using google mock
我需要模拟 linux header 中定义的宏:
#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 header 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
至于你的评论"what you mean by using #undef and re #define?":
我的意思是您需要使用您自己的宏定义来编译被测代码,这会注入一个 Google Mock class/function。
#if defined(UNDER_TEST)
#undef NLMSG_OK
#define NLMSG_OK(msg_ptr, len) \
// your mocking code
#endif
我需要模拟 linux header 中定义的宏:
#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 header 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
至于你的评论"what you mean by using #undef and re #define?":
我的意思是您需要使用您自己的宏定义来编译被测代码,这会注入一个 Google Mock class/function。
#if defined(UNDER_TEST)
#undef NLMSG_OK
#define NLMSG_OK(msg_ptr, len) \
// your mocking code
#endif