模糊测试与不变量测试
以 Foundry 作为示例框架,学习基于属性的模糊测试和不变量测试如何捕获固定单元测试遗漏的智能合约边界错误。
模糊测试与不变量测试 是 CoddyKit 上的免费 Blockchain Smart Contracts with Solidity 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Blockchain Smart Contracts with Solidity 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Blockchain Smart Contracts with Solidity 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Limits of Example Tests
You have written unit tests with specific inputs. But attackers find the one input you did not try. Fixed examples cannot cover the huge space of possible values. This is where fuzzing helps.
What Is Fuzzing?
Fuzz testing runs a test many times with randomly generated inputs. Instead of asserting on one value, you assert a property that should hold for all inputs.
A Fuzz Test in Foundry
In Foundry, any test function parameter is automatically fuzzed. The framework feeds in many random values.
function testFuzz_DepositIncreasesBalance(uint256 amount) public {
vm.assume(amount > 0 && amount < 1e30);
vault.deposit(amount);
assertEq(vault.balanceOf(address(this)), amount);
}Bounding Inputs
Random values can be absurd (like the max uint256). Use vm.assume to discard bad inputs or bound to map a value into a valid range so tests stay meaningful.
function testFuzz_Transfer(uint256 amount) public {
amount = bound(amount, 1, token.balanceOf(address(this)));
token.transfer(bob, amount);
assertEq(token.balanceOf(bob), amount);
}Thinking in Properties
The shift is from 'with input X expect Y' to 'no matter the input, this rule holds'. Common properties:
- Total supply never changes on a transfer
- A user can never withdraw more than they deposited
- Balances never underflow
What Are Invariants?
An invariant is a property that must hold after any sequence of operations, not just one call. Invariant testing fires many random function calls in random order, then checks the invariant after each step.
Declaring an Invariant
In Foundry, functions prefixed with invariant_ are checked after each randomized call sequence.
function invariant_TotalSupplyEqualsSumOfBalances() public {
assertEq(token.totalSupply(), handler.sumOfBalances());
}The Handler Pattern
Raw random calls often revert or wander into useless states. A handler contract wraps the target with guided, valid actions and tracks expected totals (ghost variables) for the invariant to check.
contract Handler {
Token token;
uint256 public sumOfBalances;
function transfer(uint256 toSeed, uint256 amount) external {
// bounded, valid transfer logic that updates ghost totals
}
}Shrinking Failures
When a fuzzer finds a failing input, it shrinks it to the simplest counterexample. This makes the bug far easier to understand and reproduce than a random gigantic number.
Tuning Test Runs
More runs find deeper bugs but take longer. Configure run counts in foundry.toml for CI versus quick local checks.
[fuzz]
runs = 1000
[invariant]
runs = 256
depth = 50When to Use Each
Use fuzzing to harden individual functions against unexpected single inputs. Use invariant testing to verify system-wide rules survive any sequence of actions. Together they catch classes of bugs fixed tests never reach.
Quick Check
Test your understanding of property-based testing.
Recap
You learned fuzzing and invariant testing:
- Fuzzing runs functions with many random inputs against properties
vm.assumeandboundkeep inputs valid- Invariants check system rules across random call sequences
- Handlers guide actions; shrinking simplifies failures
These techniques uncover edge cases that example-based tests miss.
常见问题解答
「模糊测试与不变量测试」课时是免费的吗?
是的 — 「模糊测试与不变量测试」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Blockchain Smart Contracts with Solidity 课程的其余内容,请升级到 CoddyKit PRO。 Blockchain Smart Contracts with Solidity 课程共包含 4 节课。
「模糊测试与不变量测试」这节课中我会学到什么?
以 Foundry 作为示例框架,学习基于属性的模糊测试和不变量测试如何捕获固定单元测试遗漏的智能合约边界错误。 你通过在浏览器中直接运行的动手代码来练习 Blockchain Smart Contracts with Solidity,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Blockchain Smart Contracts with Solidity 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Blockchain Smart Contracts with Solidity 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「模糊测试与不变量测试」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Blockchain Smart Contracts with Solidity 课中编写并运行代码吗?
能。每节 Blockchain Smart Contracts with Solidity 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 使用 Foundry/Hardhat 进行高级测试
- 形式化验证基础
- 主网部署与监控
- 模糊测试与不变量测试