我正在阅读几篇关于模拟 C 函数(如CMock或CMocka)的文章,但我不确定在此过程中如何用模拟函数替换实际函数。例如,CMocka 依赖于使用 GNU 编译器的自动包装,该编译器支持--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
了,那么调用 from 怎么可能myfunc.c
结束MockParseStuff.c
呢?这是否意味着我不能
parsestuff.c
包含在单元测试项目中?但如果是这种情况,那么也不可能模拟,例如,MyFunc
在myfunc.c
任何测试中,因为我已经必须包含文件才能测试它?
(更新)我也知道我可以包含.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
}
但这似乎是很多管道,我什至没有看到任何地方提到它。