CPPNIUT使用過程常見問題FAQ
Z00165390 20101225
1. 如何對函數中一次或者多次malloc函數調用進行處理
Test.c
Void foo(void)
{
A = malloc(100);
If(NULL == A)
{
Return ;
}
.. .. ....
B =malloc(100);
If(NULL == B)
{
Return ;
}
}
常規的對 malloc打樁後,走到第一個malloc就會返回,無法覆蓋第二個malloc函數。
處理方法:重構malloc函數進行封裝
定義函數void *MALLOC_ARRAY(int32 length)
{
uint8*array = NULL;
if(NULL == (array = (uint8 *)malloc( sizeof(uint8) * length )) )
{
fprintf(stdout,"Memory Exhausted\n");
returnNULL;
}
memset(array, 0, length*sizeof(uint8));
return(void*)array;
}
然後源碼調整為:
Void foo(void)
{
A = MALLOC_ARRAY (100);
.. .. .. ..
B =MALLOC_ARRAY (100);
}
然後再單獨對這個新定義的函數void *MALLOC_ARRAY(int32 length)做一次打樁處理做UT即可覆蓋Void foo(void)函數中所有的 malloc分支。
2. 對靜態函數的打樁
static靜態函數範圍的為本檔案,顯然在另外一個頁面中定義的ut函數是無法訪問源碼中定義的static函數。
處理方法:將static函數做一次封裝
Static int foo(char argc, char* argv[])
{
Return0;
}
在源檔案中對該函數進行封裝,保持參數與原函數一致
int ut_foo(char argc, char* argv[])
{
Returnfoo(argc, argv);
}
然後只要對外部可訪問的函數ut_foo做ut即可。
3、exit的處理方法
函數中使用了exit
int foo(char argc, char* argv[])
{
… …
If(NULL== a)
{
Exit;
}
Return0;
}
目前UT工具不支援直接對exit函數進行打樁,因此可以使用宏替換的方式處理。
首先在源碼中定義一個函數
Void ExitError(char* filename,uint32 linenum)
{
Printf(“[error\]%s:%d\n”, filename, linenum);
Exit;
}
然後將foo()函數中所有的exit使用
ExitError((char*)__FILE__, __LINE__); Return;替換,上述foo()函數修改為
int foo(char argc, char* argv[])
{
… …
If(NULL== a)
{
ExitError((char*)__FILE__, __LINE__);
Return -1;
}
Return0;
}
然後只要對函數ExitError進行打樁即可避免目前庫函數不能直接對exit進行打樁的限制。另外,對於這個新定義的ExitError函數中的exit函數做UT可以通過在源碼中宏替換的方式進行處理。
int utExitError (void)
{
#defineExit return
ExitError((char*)__FILE__,__LINE__);
#undef Exit// 取消宏定義,避免對其它函數處理的影響
Return0;
}