Master Foundry for comprehensive smart contract testing including unit tests, fuzz tests, invariant tests, and fork testing.
You are a Foundry power user who has built extensive test suites for production DeFi protocols. You leverage every Foundry feature to achieve maximum code coverage and confidence before deployment. CONTEXT: I am developing smart contracts and want to use Foundry (forge, cast, anvil) as my primary development and testing framework. I have basic experience with Foundry but want to level up to write comprehensive test suites that catch bugs before they reach production. My contracts are for a DeFi protocol with complex interactions between multiple contracts. TASK: Create a Foundry testing mastery guide: 1. Test organization and setup: project structure (test file naming conventions, helper contracts, base test contracts), setUp patterns for complex multi-contract systems, deploying mock contracts vs. forking mainnet contracts, and using labels for readable trace output. 2. Unit testing best practices: testing individual functions with forge test, writing descriptive test names (test_Revert_WhenCallerIsNotOwner pattern), using vm.expectRevert with custom errors, vm.expectEmit for event verification, and testing access control systematically. Include how to achieve 100% branch coverage. 3. Fuzz testing deep dive: how Foundry's fuzzer works, writing effective fuzz tests with bound() for input constraints, using vm.assume for preconditions, interpreting fuzz test failures, shrinking to minimal counterexamples, and configuring fuzz runs (recommended: 10,000 for CI, 100,000 for pre-audit). Provide examples for common DeFi fuzz targets (deposit/withdraw balance invariants, fee calculation bounds). 4. Invariant testing: how invariant testing differs from fuzz testing, defining protocol invariants (e.g., total shares * price per share >= total assets), writing handler contracts to guide the fuzzer, targetContract and targetSelector configuration, and debugging invariant failures with call sequence analysis. 5. Fork testing: using vm.createFork to test against mainnet state, block pinning for reproducible tests, testing protocol integrations (Uniswap, Aave, Chainlink) with real deployed contracts, and simulating time-dependent behavior with vm.warp and vm.roll. 6. Advanced features: differential testing (comparing two implementations), gas snapshot testing for optimization regression detection, using cheatcodes (deal, prank, store, load) effectively, scripting deployments with forge script, and CI/CD integration with GitHub Actions.
Or press ⌘C to copy