Foundry fuzz testing
A fuzz test states a property and lets Foundry search inputs for a counterexample; the value is in the property chosen, not the number of runs.
Procedure
- Write stateless fuzz tests with one named property per test:
function testFuzz_depositThenWithdraw(uint96 amount) public {
amount = uint96(bound(amount, 1, 1e30));
token.mint(address(this), amount);
vault.deposit(amount);
vault.withdraw(vault.balanceOf(address(this)));
assertGe(token.balanceOf(address(this)), amount - 1); // rounding
}
- Constrain inputs with
bound(x, lo, hi)orvm.assume; unbounded uints mostly revert and waste runs. - Configure runs in
foundry.toml:
[fuzz]
runs = 1000
max_test_rejects = 100000
fail_on_revert = true
- Use
fail_on_revert = trueso a revert is a counterexample, not a skip — but only once inputs are bound. - Add
/// forge-config: default.fuzz.runs = 10000for hot properties in CI. - Assert relations, not exact values: monotonicity (
f(a) <= f(b)whena <= b), conservation (sum(balances) == totalSupply), idempotence of views. - Reproduce a failure deterministically with the emitted seed:
forge test --match-test testFuzz_x --fuzz-seed 0x1234. - Check stateful interplay by moving invariants to an invariant test rather than a fuzz test.
- Run under the optimiser and without (
forge test --no-optimize) to catch different overflow paths. - Keep a corpus: Foundry writes failing inputs to
cache/fuzz/; commit them so the fix is regression-tested.
Pitfalls
vm.assumeon a narrow condition rejects most inputs and slows the run to a crawl; usebound.- Fuzzing a getter that cannot fail gives false confidence — fuzz state-changing paths.
fail_on_revert = false(the default) hides reverts, so an assertion after a revert is never reached.- Testing exact equality on a value that legitimately rounds; use
assertApproxEqAbs(..., 1). - Addresses from the fuzzer can be
address(0);assume(addr != address(0))before using them.
Verification
forge test --match-test "testFuzz" -vv
Pass: all fuzz tests report the configured run count with no counterexample; a shrink report shows the minimal failing input when one exists.
Report the properties fuzzed, the run count, and any counterexample with its seed.