我正在阅读几篇关于模拟C函数的文章(如CMock或CMocka),但我不确定在这个过程中实际的函数是如何被替换为模拟函数的。例如,CMocka依赖于使用GNU编译器的自动包装,支持参数如
但是,对于几乎所有其他框架,在Visual Studio中如何做到这一点呢?
例如,CMock有一个类似于此的示例(这里大大简化):
现在,在测试过程中,Ruby脚本会创建模拟函数,例如:
但这似乎需要很多管道,我甚至没有看到它在任何地方被提到。
--wrap
来在函数调用中添加__wrap
前缀,或者使用弱符号允许您覆盖任何您喜欢的符号。但是,对于几乎所有其他框架,在Visual Studio中如何做到这一点呢?
例如,CMock有一个类似于此的示例(这里大大简化):
// myfunc.c
#include <parsestuff.h>
// this is the function we would like to test
int MyFunc(char* Command)
{
// this is the call to the function we will mock
return ParseStuff(Command);
}
还有实际的实现,其中包含链接器应在实际应用程序中找到的实际函数:
// parsestuff.c
int ParseStuff(char* cmd)
{
// do some actual work
return 42;
}
现在,在测试过程中,Ruby脚本会创建模拟函数,例如:
// MockParseStuff.c (auto created by cmock)
int ParseStuff(char* Cmd);
void ParseStuff_ExpectAndReturn(char* Cmd, int toReturn);
如果VS项目已经包含
parsestuff.c
,那么从myfunc.c
调用的函数如何最终到达MockParseStuff.c
?这意味着我不能在单元测试项目中包含
parsestuff.c
吗?但是如果是这样的话,那么也无法在任何测试中模拟例如myfunc.c
中的MyFunc
,因为我已经不得不包含它以便进行测试了?
(更新) 我还知道可以包含.c
文件而非.h
文件,然后进行一些预处理操作以替换原始的调用,例如:
// replace ParseStuff with ParseStuff_wrap
#define ParseStuff ParseStuff_wrap
// include the source instead of the header
#include <myfunc.c>
#undef ParseStuff
int ParseStuff_wrap(char* cmd)
{
// this will get called from MyFunc,
// which is now statically included
}
但这似乎需要很多管道,我甚至没有看到它在任何地方被提到。