Skip to content

测试方法语法

基本语法

c
/*
 * 设计说明:描述测试的目的和设计思路
 * 预期结果:描述测试通过时的预期行为
 */
__attribute__((test_method))
int test_function_name(void) {
    // 测试逻辑
    return result == expected;  // 非零=通过, 0=失败
}

设计说明注释

每个测试函数前必须添加设计说明注释:

c
/*
 * 设计说明:测试用户名验证函数对空字符串的处理
 * 预期结果:空字符串应返回 false
 */
__attribute__((test_method))
int test_validate_empty_username(void) {
    return validate_username("") == false;
}

返回值规则

返回值含义示例
非零值测试通过return 1;
0测试失败return 0;

推荐写法

使用布尔表达式作为返回值:

c
return actual == expected;

初始化与清理

test_initialize

在每个测试函数执行之前调用:

c
static int g_counter = 0;

__attribute__((test_initialize))
int setup(void) {
    g_counter = 0;
    printf("[setup] counter reset\n");
    return 0;  // 0=成功, 非零=错误
}

test_cleanup

在每个测试函数执行之后调用:

c
__attribute__((test_cleanup))
int teardown(void) {
    printf("[cleanup] test complete\n");
    return 0;
}

执行顺序

test_initialize (setup)

test_method (test_case_1)

test_cleanup (teardown)

test_initialize (setup)

test_method (test_case_2)

test_cleanup (teardown)
    ...

完整示例

c
#include "calculator.h"
#include <stdio.h>

static int g_initialized = 0;

__attribute__((test_initialize))
int setup(void) {
    g_initialized = 1;
    printf("[setup] initializing test environment\n");
    return 0;
}

__attribute__((test_cleanup))
int teardown(void) {
    g_initialized = 0;
    printf("[cleanup] cleaning up\n");
    return 0;
}

/*
 * 设计说明:验证初始化函数被正确调用
 * 预期结果:g_initialized 应为 1
 */
__attribute__((test_method))
int test_setup_called(void) {
    return g_initialized == 1;
}

/*
 * 设计说明:测试基本加法
 * 预期结果:1 + 2 = 3
 */
__attribute__((test_method))
int test_add(void) {
    return calc_add(1, 2) == 3;
}

/*
 * 设计说明:测试基本减法
 * 预期结果:5 - 3 = 2
 */
__attribute__((test_method))
int test_subtract(void) {
    return calc_subtract(5, 3) == 2;
}

/*
 * 设计说明:测试除零处理
 * 预期结果:除以零返回 0(安全处理)
 */
__attribute__((test_method))
int test_divide_by_zero(void) {
    return calc_divide(10, 0) == 0;
}

// includes: -I../include
// timeout: 10s

属性限制

属性每文件数量函数签名
test_method无限制int func(void)
test_initialize最多 1 个int func(void)
test_cleanup最多 1 个int func(void)

常见错误

错误:忘记返回值

c
// 错误:没有返回值
__attribute__((test_method))
int test_bad(void) {
    int result = add(1, 2);
    // 忘记 return!
}

错误:使用 void 返回类型

c
// 错误:必须返回 int
__attribute__((test_method))
void test_bad(void) {  // ❌ void 不行
    // ...
}

错误:带参数的测试函数

c
// 错误:测试函数不能有参数(除非使用参数化测试)
__attribute__((test_method))
int test_bad(int value) {  // ❌ 普通测试不能有参数
    return value > 0;
}

参数化测试

如果需要带参数的测试,请参阅 参数化测试

本页面内容遵循 Luna 软件源代码授权条款 (LSLA) 发布