Appearance
测试定义
本章介绍如何使用 Anvil 编写测试用例。
概述
Anvil 测试是标准的 C 函数,通过 GCC 属性标记进行自动发现。核心理念是「测试即代码」——测试函数和普通 C 函数一样编写,只需添加特定属性。
核心特性
自动发现
无需手动注册测试。Anvil 会扫描测试目录中的所有 .c 文件,自动发现带有 test_method 属性的函数。
c
// 这个函数会被自动发现并执行
__attribute__((test_method))
int test_example(void) {
return 1; // 通过
}返回值语义
| 返回值 | 含义 |
|---|---|
| 非零值 | 测试通过 |
| 0 | 测试失败 |
三种属性
| 属性 | 用途 | 每个文件数量 |
|---|---|---|
test_method | 标记测试函数 | 可多个 |
test_initialize | 测试前初始化 | 0 或 1 |
test_cleanup | 测试后清理 | 0 或 1 |
快速示例
c
#include "my_module.h"
// 初始化函数(可选)
__attribute__((test_initialize))
int setup(void) {
// 在每个测试前执行
return 0; // 0=成功
}
// 清理函数(可选)
__attribute__((test_cleanup))
int cleanup(void) {
// 在每个测试后执行
return 0;
}
/*
* 设计说明:测试基本加法功能
* 预期结果:2 + 3 应返回 5
*/
__attribute__((test_method))
int test_add(void) {
return add(2, 3) == 5;
}
/*
* 设计说明:测试边界情况
* 预期结果:INT_MAX + 1 应溢出
*/
__attribute__((test_method))
int test_overflow(void) {
return add(INT_MAX, 1) < 0;
}
// 指定编译选项
// includes: -I../include
// flags: -Wall
// timeout: 5s