CPPNIUT使用過程常見問題FAQ

來源:互聯網
上載者:User

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;

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.