2. 测试驱动开发入门
任务说明
本案例以TDD(测试驱动开发)方式开发一个简单的计算器模块。任务闭环为:先编写针对加法与除法功能的单元测试,再实现计算器代码使测试通过,最后运行测试验证结果。整个过程遵循“红-绿-重构”节奏,但本案例聚焦前两步,不涉及重构扩展。
第一步:编写测试(红)
创建测试文件 test_calculator.c,使用C语言轻量测试框架(仅依赖assert.h,无需第三方库)。测试覆盖两个核心行为:add函数正确计算两数之和;divide函数在除数为零时返回0(约定错误码),非零时返回商。
// test_calculator.c
#include <assert.h>
#include <stdio.h>
#include "calculator.h"
void test_add_positive_numbers(void) {
assert(add(2, 3) == 5);
}
void test_add_negative_numbers(void) {
assert(add(-2, -3) == -5);
}
void test_divide_normal_case(void) {
assert(divide(10, 2) == 5);
}
void test_divide_by_zero_returns_zero(void) {
assert(divide(10, 0) == 0);
}
int main(void) {
test_add_positive_numbers();
test_add_negative_numbers();
test_divide_normal_case();
test_divide_by_zero_returns_zero();
printf("所有测试通过\n");
return 0;
}
第二步:实现功能(绿)
创建头文件 calculator.h 声明接口,以及源文件 calculator.c 实现函数。此时才编写实际逻辑,使测试通过。
// calculator.h
#ifndef CALCULATOR_H
#define CALCULATOR_H
int add(int a, int b);
int divide(int a, int b);
#endif
// calculator.c
#include "calculator.h"
int add(int a, int b) {
return a + b;
}
int divide(int a, int b) {
if (b == 0) {
return 0; // 约定:除零返回0
}
return a / b;
}
第三步:编译与验证
在命令行执行以下命令,编译并运行测试:
gcc -Wall -o test_calculator test_calculator.c calculator.c
./test_calculator
预期输出为:
所有测试通过
若测试失败,assert会中止程序并报告失败行号,此时应回到实现代码修正逻辑,直至测试全部通过。
判定标准
执行 ./test_calculator 后,若终端输出“所有测试通过”且程序退出码为0,则判定本案例完成。若出现断言失败,说明实现与测试预期不符,需检查calculator.c中的逻辑并修正后重新编译运行。