Skip to content

组合策略

多参数测试时,使用 strategy() 控制参数组合方式。

策略对比

策略语法说明组合数量
笛卡尔积默认所有参数值的完全组合n1 × n2 × ...
Pairwisestrategy(pairwise)任意两参数组合至少出现一次显著减少
Zipstrategy(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² = 9

Zip 适用场景

  • 输入和预期输出一一对应
  • 测试表驱动测试
  • 数据有明确配对关系

策略选择指南

场景推荐策略
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(估算)
252525(无优化)
3512515-25
4562520-30
55312525-40
310100030-50
4101000050-80

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