CUnit詳解(基于linux下的白盒單元測(cè)試)
CUnit是一個(gè)對(duì)C語(yǔ)言編寫的程序進(jìn)行單元測(cè)試的框架,在線文檔說(shuō)它作為一個(gè)靜態(tài)鏈接庫(kù)被鏈接到用戶的測(cè)試代碼中。
它提供了一種簡(jiǎn)潔的框架來(lái)建立測(cè)試架構(gòu),并提供豐富的斷言(Assertion)來(lái)測(cè)試通用數(shù)據(jù)類型。除此之外,它還提供了
許多不同的結(jié)構(gòu)來(lái)運(yùn)行測(cè)試用例和報(bào)告測(cè)試結(jié)果。
(1)CUnit的架構(gòu)
可以看出Cunit也是有組織的,主要分幾個(gè)角色,Registry,Suite及Test方法。可以通過(guò)下面例子,體會(huì)到這種組織關(guān)系。
按官方文檔說(shuō)明,使用Cunit的主要步驟有:
1) Write functions for tests (and suite init/cleanup if necessary).
2) Initialize the test registry - CU_initialize_registry()
3) Add suites to the test registry - CU_add_suite()
4) Add tests to the suites - CU_add_test()
5) Run tests using an appropriate interface, e.g. CU_console_run_tests
6) Cleanup the test registry - CU_cleanup_registry
(2)測(cè)試模式
下面是四種測(cè)試模式:
1 Automated Output to xml file??????????? Non-interactive
2 Basic????? Flexible programming??????? interface Non-interactive?
3 Console??? Console interface (ansi C)???? Interactive?
4 Curses???? Graphical interface (Unix)???? Interactive
第一種模式是將結(jié)果輸出到XML文檔中,便于生成報(bào)告。第二種模式是每一次運(yùn)行結(jié)束之后在standard output中顯示測(cè)試結(jié)果,不能保留測(cè)試結(jié)果數(shù)據(jù)。第三種模式是console方式的,可以人機(jī)交互;前兩種模式是非交互式的。第四種只在Unix中使用。
(3)測(cè)試的基本流程
1)編寫單元測(cè)試函數(shù)(有必要的話要寫suite的init/cleanup函數(shù))。Write functions for tests (and suite init/cleanup if necessary).
2)調(diào)用函數(shù)CU_initialize_registry()初始化測(cè)試注冊(cè)單元(Test Registry)。 Initialize the test registry - CU_initialize_registry()
3)調(diào)用函數(shù)CU_add_suite() 將測(cè)試包(suite)添加到測(cè)試注冊(cè)單元(Test Registry)中。Add suites to the test registry - CU_add_suite()
4)調(diào)用函數(shù)CU_add_test()將測(cè)試用例添加到測(cè)試包(suite)中。Add tests to the suites - CU_add_test()
5)使用合適的接口來(lái)運(yùn)行測(cè)試用例。Run tests using an appropriate interface, e.g. CU_console_run_tests
6)調(diào)用函數(shù)CU_cleanup_registry清除測(cè)試注冊(cè)單元(Test Registry)。Cleanup the test registry - CU_cleanup_registry()
先編寫一個(gè)具體兩個(gè)簡(jiǎn)單功能的函數(shù),然后寫Testcase來(lái)測(cè)試它。
文件主要有:
1) strformat.h :字符串功能函數(shù)的接口文件
2)strformat.c :字符串功能函數(shù)的實(shí)現(xiàn)
3)testcase.c : 測(cè)試用例及Cunit運(yùn)行環(huán)境
4)makefile :
直接上代碼吧,strformat.h
#ifndef _strformat_h
#define _strformat_h
typedef char * string;
int string_lenth(string word);
string to_Upper(string word);
string add_str(string word1 ,string word2);
#endif
strformat.c
#include
#include
#include
#include
#include
#include
#include
#include
#include "strformat.h"
/**************************************************************************
函數(shù)名稱:字符串相加
**************************************************************************/
string add_str(string word1 ,string word2){
return (strcat(word1, word2));
}
/**************************************************************************
函數(shù)名稱:將字符串轉(zhuǎn)換成大寫格式
**************************************************************************/
string to_Upper(string word){
int i;
for(i = 0;word[i] !='