1. 程式人生 > >使用CUnit寫測試程式的一般步驟

使用CUnit寫測試程式的一般步驟

A.

使用CUnix寫測試程式的一般步驟
------------------------------------
1.
編寫測試函式。
2.
編寫setup/clearup函式。-在執行Suite的前後呼叫。

(

A typical sequence of steps for using the CUnit framework is:

1. Write functions for tests (and suite init/cleanup if necessary).

3. Add suites to the test registry -

4. Add tests to the suites -

5. Run tests using an appropriate interface, e.g.

)

B.

Cunit結構如下:

Test Registry
|
------------------------------
||
Suite '1'. . . .Suite 'N'
||
------------------------------
||||
Test '11' ... Test '1M'Test 'N1' ... Test 'NM'

C.

以上說明為一般步驟,比較繁複一點。但實際上,可以使用CUNITshortcut模式來編寫測試程式。

即自己直接編寫測試集合(suites

),各個單測試組(suite),實現各個測試函式。

0. 編寫測試函式

void testFatal(void)

{

CU_TEST_FATAL(CU_TRUE);

fprintf(stderr, "/nFatal assertion failed to abort test in testFatal/n");

exit(1);

}

1. 單個測試組(test_array)的定義

CU_TestInfo tests_fata_test_arrayl[] =

{

{ "testFatal", testFatal },

//測試函式名測試函式名實現

CU_TEST_INFO_NULL,

};

//

單個測試suite中可以有很多個測試函式

2. 定義測試集suites.

CU_SuiteInfo suites[] =

{

#if 0

{ "suite_success_both",suite_success_init, suite_success_clean, tests_success },

{ "suite_success_init",suite_success_init, NULL,tests_success },

{ "suite_success_clean", NULL,suite_success_clean, tests_success },

{ "test_failure",NULL,NULL,tests_failure },

{ "suite_failure_both",suite_failure_init, suite_failure_clean, tests_suitefailure }, /* tests should not run */

{ "suite_failure_init", suite_failure_init, NULL,tests_suitefailure }, /* tests should not run */

#endif

{ "TestFatal",NULL,NULL,tests_fata_test_arrayl },

//測試組(suite)的名字,測試組初始化函式,測試組清除函式,單個測試組(test_array)的定義

CU_SUITE_INFO_NULL,

};

3. 註冊測試suites.

/* Register suites. */

if (CU_register_suites(suites) != CUE_SUCCESS)

{

fprintf(stderr, "suite registration failed - %s/n",

CU_get_error_msg());

exit(EXIT_FAILURE);

}

D.

至此前期的主要準備工作已經完成,但是要使用cuint還需要一些步驟:

Cunit 被編譯成靜態庫,測試時使用該庫提供的測試工具集。此外在執行測試程式時,CUint提供了幾種不同的介面:

Automated

Output to xml file

Non-interactive

Basic

Flexible programming interface

Non-interactive

Console

Console interface (ansi C)

Interactive

Curses

Graphical interface (Unix)

Interactive

Console是可以人機互動的。

console模式下構建測試程式:

1.

編寫main()函式,一般格式如下:

int main(int argc, char* argv[])

{

/*初始化registry */

if (CUE_SUCCESS != CU_initialize_registry())

return CU_get_error();

// registry在使用前必須初始化,使用者需要在呼叫任何Cunit函式之前呼叫該函式。

/* Register all suites and tests */

if (CUE_SUCCESS != CU_register_suites(suites))

{

CU_cleanup_registry();

return CU_get_error();

}

//所有以CU_SuiteInfo定義的測試組都可以通過單次呼叫上述函式註冊

/*** This starts the test run: */

CU_console_run_tests();//run all tests

//console模式執行所有的測試case

CU_cleanup_registry();

return CU_get_error();

}