Chapter 11

Fuzz and Invariant Testing

Unit tests prove your code handles the cases you thought to write. Fuzz tests feed random inputs into functions and check invariants — properties that must always hold — surfacing edge cases like overflow boundaries and zero-value transfers that manual tests miss.

Bound fuzz inputs with vm.assume or typed parameters — unbounded uint256 values often hit unrealistic paths. Focus invariants on economic properties: total supply conservation, no unauthorized balance increases, and collateral ratios that never go negative.

Invariant tests deploy a handler contract that randomly calls your protocol functions in sequence. The test runner checks global properties after every call batch, simulating weeks of adversarial usage in seconds.