属性测试
一句话解释
属性测试用随机输入检查通用属性——不是测试特定用例,而是测试规则是否始终成立。
用大白话说
属性测试颠覆了传统测试。不是写特定示例(测试 add(2, 3) === 5),而是声明应始终成立的通用属性,框架用数百个随机输入测试它们。属性示例:
- 交换律:add(a, b) === add(b, a) 对所有 a, b
- 单位元:add(a, 0) === a 对所有 a
- 结合律:add(add(a, b), c) === add(a, add(b, c))
- 不崩溃:sort(array) 对任何数组都不抛异常
- 幂等性:sort(sort(array)) === sort(array)
框架生成随机输入,运行代码,检查属性。如果找到反例,它会「缩小」到最简单的失败用例(例如,发现 add(-1, 0) 失败而非 add(-847293, 0))。工具:fast-check(JS/TS)、Hypothesis(Python)、QuickCheck(Haskell)、jqwik(Java)。
示例
javascript
import fc from 'fast-check';
// Example-based test (only tests one case)
test('add(2, 3) = 5', () => {
expect(add(2, 3)).toBe(5);
});
// Property-based test (tests 100+ random cases)
test('addition is commutative', () => {
fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => {
return add(a, b) === add(b, a);
}));
});
test('addition identity: a + 0 = a', () => {
fc.assert(fc.property(fc.integer(), (a) => {
return add(a, 0)1) === a;
}));
});
// If a counterexample is found, fast-check shrinks it:
// "Failed after 42 tests with [-847, 0]"
// Shrunk: "Failed with [-1, 0]" (simplest failing case)不是特定示例,而是声明属性(规则),框架用随机输入测试它们。反例被缩小到最小失败用例。
常见混淆
容易混淆的对象: fuzz testing
关键区别: 属性测试检查特定属性/不变量对随机输入是否成立——它有断言。模糊测试只是输入随机/畸形数据看程序是否崩溃——它检查崩溃,不检查正确性。属性测试更精确;模糊测试更具探索性。
相关术语
相关资源
相关课程
- Advanced Testing
属性测试。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。