Ore*_*ols 5 c unit-testing mocking linux-device-driver linux-kernel
我正在编写一个单元测试来检查一些 API 调用。我正在使用检查进行测试。我的模块是用 CMake 构建的(如果重要的话,idk)。
我的测试调用一个函数(我需要测试),这个函数调用另一个二进制文件。
它的简化版本看起来像这样。
/* unitTest.c */
#include "libraryAPI.h"
void letsMakeACall(void)
{
ck_assert_eq(foo("water"), 0);
}
-- Module I am working on---
/*libraryAPI.c*/
#include "legacyLib.h"
void foo(const char *drink )
{
if (checkDrink(drink)!=0)
{
return 1;
}else
{
return 0;
}
}
----LEGACY BINARY---
/*legacyLib.c*/
static const char* expected = "water";
void checkDrink(const char *drink)
{
if(drink == expected)
{
/*There are also a dozen functions being called which depend on legacy module initialisation*/
return 0;
}else{
return 1;
}
}
Run Code Online (Sandbox Code Playgroud)
我想模拟来自 legacyLib 的响应,否则它会调用数十个函数并中断。我最初的想法是在运行测试时添加一些 ifdef 条件,但这违反了指导方针。因为它基本上是呼叫拦截,所以我不知道它是最佳(或有效)解决方案。我可以用什么来解决它?
我也不确定一般如何解决这个问题,我已经发布了一个类似的问题,但在某些情况下,您可以执行以下操作(假设您正在测试单个功能):
包含.c文件而不是 header .h,但在使用定义指令“重命名”模拟函数后:
#define checkDrink checkDrink_mocked
// preprocessor will now replace all occurrences of "checkDrink"
// with "checkDrink_mocked"
int checkDrink_mocked(const char *drink);
#include "legacyLib.c"
#undef checkDrink
Run Code Online (Sandbox Code Playgroud)实现重命名的函数:
int checkDrink_mocked(const char *drink)
{
return 15;
}
Run Code Online (Sandbox Code Playgroud)