Fuzzing and Invariants
Property testing.
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);
}All lessons in this course
- Foundry vs Hardhat
- forge Testing
- Fuzzing and Invariants
- cast and anvil