Appearance
组合策略
多参数测试时,使用 strategy() 控制参数组合方式。
策略对比
| 策略 | 语法 | 说明 | 组合数量 |
|---|---|---|---|
| 笛卡尔积 | 默认 | 所有参数值的完全组合 | n1 × n2 × ... |
| Pairwise | strategy(pairwise) | 任意两参数组合至少出现一次 | 显著减少 |
| Zip | strategy(zip) | 按索引配对 | min(n1, n2, ...) |
笛卡尔积(默认)
生成所有参数值的完全组合:
c
__attribute__((test_method,
params(x = {0, 1, 2}, y = {0, 1, 2})))
int test_cartesian(int x, int y) {
return compute(x, y) >= 0;
}生成 3×3=9 个测试用例:
test_cartesian[x=0, y=0]
test_cartesian[x=0, y=1]
test_cartesian[x=0, y=2]
test_cartesian[x=1, y=0]
test_cartesian[x=1, y=1]
test_cartesian[x=1, y=2]
test_cartesian[x=2, y=0]
test_cartesian[x=2, y=1]
test_cartesian[x=2, y=2]Pairwise 策略
确保任意两个参数的组合至少出现一次:
c
__attribute__((test_method,
params(a = {1,2,3,4,5}, b = {1,2,3,4,5}, c = {1,2,3,4,5}),
strategy(pairwise)))
int test_pairwise(int a, int b, int c) {
return compute(a, b, c) >= 0;
}| 策略 | 组合数量 |
|---|---|
| 笛卡尔积 | 5×5×5 = 125 |
| Pairwise | 约 15-25 |
Pairwise 适用场景
- 参数数量多(3个以上)
- 每个参数值较多
- 完全组合测试成本高
- 统计上覆盖大部分缺陷
研究表明
大多数软件缺陷由 1-2 个参数的交互引起。Pairwise 测试可以发现大部分这类缺陷。
Zip 策略
按索引配对参数值:
c
__attribute__((test_method,
params(input = {1, 2, 3}, expected = {1, 4, 9}),
strategy(zip)))
int test_square(int input, int expected) {
return math_square(input) == expected;
}生成 3 个测试用例:
test_square[input=1, expected=1] // 1² = 1
test_square[input=2, expected=4] // 2² = 4
test_square[input=3, expected=9] // 3² = 9Zip 适用场景
- 输入和预期输出一一对应
- 测试表驱动测试
- 数据有明确配对关系
策略选择指南
| 场景 | 推荐策略 |
|---|---|
| 2个参数,值较少 | 笛卡尔积 |
| 3+个参数 | Pairwise |
| 输入/输出配对 | Zip |
| 边界值测试 | 笛卡尔积或 Pairwise |
| 回归测试数据 | Zip |
完整示例
坐标边界测试(Pairwise)
c
/*
* 设计说明:测试二维坐标边界检查
* 预期结果:坐标在 [0, 100) 范围内时返回 true
*/
__attribute__((test_method,
params(
x = {-1, 0, 50, 99, 100},
y = {-1, 0, 50, 99, 100}
),
strategy(pairwise)))
int test_bounds_check(int x, int y) {
int result = is_in_bounds(x, y, 100, 100);
int expected = (x >= 0 && x < 100 && y >= 0 && y < 100);
return result == expected;
}数学函数测试(Zip)
c
/*
* 设计说明:测试阶乘函数
* 预期结果:返回正确的阶乘值
*/
__attribute__((test_method,
params(
n = {0, 1, 2, 3, 4, 5},
expected = {1, 1, 2, 6, 24, 120}
),
strategy(zip)))
int test_factorial(int n, int expected) {
return factorial(n) == expected;
}三参数测试(Pairwise)
c
/*
* 设计说明:测试 RGB 颜色验证
* 预期结果:每个分量应在 0-255 范围内
*/
__attribute__((test_method,
params(
r = boundary(uint8),
g = boundary(uint8),
b = boundary(uint8)
),
strategy(pairwise)))
int test_valid_rgb(int r, int g, int b) {
int result = is_valid_rgb(r, g, b);
int expected = (r >= 0 && r <= 255 &&
g >= 0 && g <= 255 &&
b >= 0 && b <= 255);
return result == expected;
}组合数量估算
| 参数数量 | 每参数值数 | 笛卡尔积 | Pairwise(估算) |
|---|---|---|---|
| 2 | 5 | 25 | 25(无优化) |
| 3 | 5 | 125 | 15-25 |
| 4 | 5 | 625 | 20-30 |
| 5 | 5 | 3125 | 25-40 |
| 3 | 10 | 1000 | 30-50 |
| 4 | 10 | 10000 | 50-80 |