Web3 & DApp Development Fundamentals · 课时

模糊测试与不变量

基于属性的测试

第 3 / 4 课13 个步骤

模糊测试与不变量 是 CoddyKit 上的免费 Web3 & DApp Development Fundamentals 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Web3 & DApp Development Fundamentals 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Web3 & DApp Development Fundamentals 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Beyond Hardcoded Inputs

Unit tests check specific inputs you thought of. But bugs often hide in inputs you did not think of. Property-based testing flips this: you state a property that should always hold, and the tool generates many random inputs trying to break it.

Foundry supports two flavors: fuzz tests and invariant tests.

Writing a Fuzz Test

A fuzz test is simply a test function with parameters. Foundry automatically calls it many times with randomized argument values, hunting for a counterexample.

function testFuzzDeposit(uint256 amount) public {
    vm.assume(amount > 0 && amount < 1e30);
    vault.deposit(amount);
    assertEq(vault.balanceOf(address(this)), amount);
}

Bounding Inputs

Random inputs may be unrealistic. Constrain them with:

  • vm.assume(cond) — discard runs that fail the condition
  • bound(x, min, max) — map any value into a range

Prefer bound for ranges since assume can waste runs by rejecting too many inputs.

function testFuzz(uint256 x) public {
    x = bound(x, 1, 1000); // always in [1, 1000]
    // ...
}

What Makes a Good Property

A good fuzz property is a statement that must hold for all valid inputs. Examples:

  • Depositing then withdrawing returns the same amount
  • Total supply never changes on a transfer
  • A user can never withdraw more than they deposited

Think in terms of universal truths, not specific values.

function testFuzzTransferConservesSupply(uint256 amt) public {
    uint256 supplyBefore = token.totalSupply();
    token.transfer(bob, bound(amt, 0, token.balanceOf(address(this))));
    assertEq(token.totalSupply(), supplyBefore);
}

Reading Fuzz Output

When a fuzz test fails, Foundry prints the exact counterexample that broke the property and the number of runs. It also stores a corpus so the failing input is replayed on future runs until you fix it.

$ forge test
[FAIL. Reason: assertion failed]
  Counterexample: calldata=0x..., args=[115792089237316195...]

Configuring the Fuzzer

Control fuzzing in foundry.toml. The runs setting is how many random inputs each fuzz test gets. More runs increase confidence but take longer.

# foundry.toml
[fuzz]
runs = 1000
max_test_rejects = 65536

Invariant Testing

Invariants go a step further. Instead of one function call, Foundry executes long random sequences of calls to your contract, then checks that a property still holds after every sequence.

Invariant functions are named with the invariant_ prefix.

function invariant_totalSupplyConstant() public {
    assertEq(token.totalSupply(), INITIAL_SUPPLY);
}

Handlers

For meaningful invariant tests you usually write a handler contract that exposes a curated set of actions. The fuzzer calls the handler's functions in random order, keeping the call sequences valid and focused.

Register target contracts with targetContract in setUp().

function setUp() public {
    handler = new Handler(token);
    targetContract(address(handler));
}

Ghost Variables

Handlers often track ghost variables: bookkeeping totals updated as actions run. Invariants compare the contract's real state against these ghost values.

For example, summing every deposit in the handler and asserting it equals the vault's total assets catches accounting drift.

// inside handler
uint256 public ghostTotalDeposited;
function deposit(uint256 a) external {
    vault.deposit(a);
    ghostTotalDeposited += a;
}

Fuzz vs Invariant

Knowing which to reach for:

  • Fuzz tests a single function against random arguments — good for input validation and pure logic
  • Invariant tests random sequences of actions — good for stateful systems like vaults, AMMs, and token accounting

Use both: fuzz for unit-level properties, invariants for system-level guarantees.

Best Practices

Effective property testing:

  • State properties as universal truths, not examples
  • Use bound over heavy assume
  • Increase runs for critical contracts
  • Write focused handlers for invariants
  • Track ghost variables for accounting checks

Property tests catch the edge cases humans miss.

Quick Check

What is the key difference between a fuzz test and an invariant test in Foundry?

Recap

You learned property-based testing:

  • Fuzz tests take parameters; Foundry generates random inputs
  • Use bound and vm.assume to constrain inputs
  • Invariant tests run random call sequences via handlers
  • Ghost variables track expected state for accounting invariants
  • Counterexamples are saved and replayed

Next: the cast and anvil CLI tools.

免费开始

用 AI 导师学习 Web3 & DApp Development Fundamentals — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
29
课程
105

常见问题解答

「模糊测试与不变量」课时是免费的吗?

是的 — 「模糊测试与不变量」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web3 & DApp Development Fundamentals 课程的其余内容,请升级到 CoddyKit PRO。 Web3 & DApp Development Fundamentals 课程共包含 4 节课。

「模糊测试与不变量」这节课中我会学到什么?

基于属性的测试 你通过在浏览器中直接运行的动手代码来练习 Web3 & DApp Development Fundamentals,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Web3 & DApp Development Fundamentals 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Web3 & DApp Development Fundamentals 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「模糊测试与不变量」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Web3 & DApp Development Fundamentals 课中编写并运行代码吗?

能。每节 Web3 & DApp Development Fundamentals 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Foundry 与 Hardhat 对比
  2. forge 测试
  3. 模糊测试与不变量
  4. cast 与 anvil
← 返回 Web3 & DApp Development Fundamentals