6.3 框架错误的行为

  当错误发生时,默认的行为是设置错误码并继续执行。断言失败并不认为是错误。错误包括测试包初始化或清理失败、显示地执行非活动状态的测试包或测试用例等。用户有可能倾向于当框架错误发生时停止测试,CUnit提供下面函数设置:

  void CU_set_error_action(CU_ErrorAction action)

  CU_ErrorAction CU_get_error_action(void)

  错误行为码定义如下:

  CUEA_IGNORE Run should be continued when an error condition occurs (default)

  CUEA_FAIL Run should be stopped when an error condition occurs

  CUEA_ABORT The application should exit() when an error conditions occurs

  7. 示例

  7.1 待测试模块代码

// module.h
#ifndef _MODULE_H_
#define _MODULE_H_
int add(int, int);
int sub(int, int);
#endif
// module.c
#include "module.h"
int add(int a, int b)
{
return a+b;
}
int sub(int a, int b)
{
return a-b;
}

  7.2 测试用例及其运行代码

// TestRun.c
#include <CUnit/CUnit.h>
#include <CUnit/Basic.h>
#include <CUnit/Console.h>
#include <CUnit/CUCurses.h>
#include "module.h"
void test_add1(void){
CU_ASSERT_EQUAL(add(1,2),3);
}
void test_add2(void){
CU_ASSERT_NOT_EQUAL(add(1,2),4);
}
void test_sub1(void){
CU_ASSERT_EQUAL(sub(1,2),-1);
}
void test_sub2(void){
CU_ASSERT_NOT_EQUAL(sub(1,2),0);
}
CU_TestInfo testcase1[] = {
{"test_for_add1:",test_add1},
{"test_for_add2:",test_add2},
CU_TEST_INFO_NULL
};
CU_TestInfo testcase2[] = {
{"test_for_sub1:",test_sub1},
{"test_for_sub2:",test_sub2},
CU_TEST_INFO_NULL
};
int suite_init(void){
return 0;
}
int suite_cleanup(void){
return 0;
}
CU_SuiteInfo suites[] = {
{"testSuite1",suite_init,suite_cleanup,testcase1},
{"testsuite2",suite_init,suite_cleanup,testcase2},
CU_SUITE_INFO_NULL
};
int main(int argc, char * argv[])
{
if(CU_initialize_registry()){
fprintf(stderr, " Initialization of Test Registry failed. ");
return CU_get_error();
}else{
if(CUE_SUCCESS != CU_register_suites(suites))
return CU_get_error();
//**** Automated Mode *****************
CU_set_output_filename("ModuleTest");
CU_list_tests_to_file();
CU_automated_run_tests();
//************************************/
/***** Basice Mode *******************
CU_basic_set_mode(CU_BRM_VERBOSE);
CU_basic_run_tests();
//************************************/
/*****Console Mode ********************
CU_console_run_tests();
//************************************/
/*****Curse Mode ********************
CU_curses_run_tests();
//*********************************/
CU_cleanup_registry();
return CU_get_error();
}
}
// Makefile
INC=-I/local/local/include
LIB=-L/local/local/lib
all: module.c TestRun.c
gcc $^ -o TestRun $(INC) $(LIB) -lcunit -lcurses -static
clean:
rm TestRun