A comprehensive guide to advanced testing patterns in Foundry for Ethereum smart contract development. This repository contains all the code examples and patterns discussed in my Medium blog series.
I've written an in-depth article about advanced Foundry testing patterns. Read it on Medium:
Advanced Foundry Testing Patterns: A Complete Guide
This repository serves as the companion code for the blog post, providing working examples of all the patterns and techniques discussed.
This guide covers advanced testing patterns that go beyond basic unit tests:
- β State tree testing
- β Time-based testing patterns
- β Access control testing
- β
Event testing with
vm.expectEmit - β Snapshot and rollback patterns
- π Fuzz testing with bounds and assumptions
- π Invariant testing with handlers
- π΄ Fork testing with mainnet state
- π Security pattern testing (reentrancy, access control)
- π Gas optimization testing
- π Differential testing
- π Mock and stub patterns
- πΈ DeFi protocol integration testing
- π Cross-chain bridge testing
- β¬οΈ Proxy and upgradeability testing
- π¨ Attack vector testing
- π° Multi-user stateful fuzzing
- foundry-advanced-guide.md - Core testing patterns and fundamentals
- foundry-real-world-examples.md - Production scenarios and security testing
All examples are fully functional and can be run with Foundry.
Make sure you have Foundry installed:
curl -L https://foundry.paradigm.xyz | bash
foundryup- Clone the repository:
git clone https://github.com/jmakwana0x1/foundry-advanced-testing.git
cd foundry-advanced-testing- Install dependencies:
forge install- Run the tests:
forge test# Run all tests
forge test
# Run tests with gas reporting
forge test --gas-report
# Run specific test file
forge test --match-path test/ReentrancyTest.t.sol
# Run with verbosity for detailed output
forge test -vvvv
# Run fuzz tests only
forge test --match-test testFuzz
# Run invariant tests
forge test --match-test invariant
# Generate coverage report
forge coverage
# Create gas snapshot
forge snapshotLearn the fundamentals of writing effective Foundry tests:
- Setting up test environments
- Using cheat codes (
vm.prank,vm.warp,vm.roll) - Assertions and expectations
- Test organization
Master property-based testing:
- Bounded fuzzing with
bound() - Using assumptions with
vm.assume() - Testing invariants across random inputs
- Structured fuzzing strategies
Build robust invariant test suites:
- Handler-based testing
- Ghost variables for tracking
- Multi-actor scenarios
- Stateful fuzzing patterns
Test against real deployed contracts:
- Creating and managing forks
- Impersonating accounts
- Testing with live data
- Multi-chain testing
Identify vulnerabilities:
- Reentrancy attack patterns
- Access control bypass testing
- Flash loan manipulation
- Integer overflow/underflow
- Front-running scenarios
Optimize your contracts:
- Gas profiling techniques
- Comparative gas analysis
- Snapshot-based regression testing
- Identifying optimization opportunities
foundry-advanced-testing/
βββ README.md
βββ foundry-advanced-guide.md
βββ foundry-real-world-examples.md
βββ foundry.toml
βββ src/
β βββ examples/
β β βββ Token.sol
β β βββ Vault.sol
β β βββ LendingPool.sol
β β βββ AMM.sol
β β βββ ...
β βββ security/
β βββ VulnerableBank.sol
β βββ ProtectedBank.sol
β βββ ...
βββ test/
βββ unit/
β βββ Token.t.sol
β βββ Vault.t.sol
βββ integration/
β βββ DeFiIntegration.t.sol
β βββ MultiContract.t.sol
βββ invariant/
β βββ BankInvariant.t.sol
β βββ AMMInvariant.t.sol
βββ fork/
β βββ MainnetFork.t.sol
βββ security/
βββ ReentrancyTest.t.sol
βββ AccessControlTest.t.sol
| Cheat Code | Purpose | Example |
|---|---|---|
vm.prank(address) |
Set msg.sender for next call | vm.prank(alice); token.transfer(bob, 100); |
vm.startPrank(address) |
Set msg.sender for all calls | vm.startPrank(alice); |
vm.warp(timestamp) |
Set block.timestamp | vm.warp(block.timestamp + 1 days); |
vm.roll(number) |
Set block.number | vm.roll(block.number + 100); |
vm.deal(address, amount) |
Set ETH balance | vm.deal(alice, 100 ether); |
vm.expectRevert() |
Expect next call to revert | vm.expectRevert("Error"); |
vm.expectEmit() |
Expect event emission | vm.expectEmit(true, true, false, true); |
test_Description() // Basic test
testFail_Description() // Expected to fail (deprecated, use expectRevert)
testRevert_Description() // Expect revert with reason
testFuzz_Description(args) // Fuzz test
invariant_Description() // Invariant test- Start with the basics - Read
foundry-advanced-guide.mdsections 1-3 - Try simple examples - Run the unit tests
- Explore fuzzing - Understand property-based testing
- Master invariants - Build handler-based test suites
- Real-world scenarios - Study
foundry-real-world-examples.md - Security focus - Learn attack vectors and defenses
[profile.default]
src = "src"
out = "out"
libs = ["lib"]
solc_version = "0.8.24"
[profile.default.fuzz]
runs = 256
max_test_rejects = 65536
[profile.default.invariant]
runs = 256
depth = 15
fail_on_revert = false
[profile.ci]
fuzz = { runs = 5000 }
invariant = { runs = 1000 }$ forge test --gas-report
Running 47 tests for test/Token.t.sol:TokenTest
[PASS] test_Mint() (gas: 45123)
[PASS] test_Transfer() (gas: 67234)
[PASS] testFuzz_TransferAmounts(uint256) (runs: 256, ΞΌ: 65432, ~: 65234)
[PASS] invariant_totalSupplyEqualsBalances() (runs: 256, calls: 3840, reverts: 156)
Test result: ok. 47 passed; 0 failed; finished in 2.34s
| Contract | Function | Gas |
|----------|---------------|---------|
| Token | mint | 45123 |
| Token | transfer | 67234 |
| Token | approve | 44567 |While this is primarily an educational repository for my blog post, I welcome:
- π Bug reports
- π‘ Suggestions for additional patterns
- π Improvements to documentation
- β¨ Additional examples
Please open an issue or submit a pull request!
- Medium: @YOUR_MEDIUM_USERNAME
- Twitter: @YOUR_TWITTER
- GitHub: @YOUR_GITHUB
If you found this guide helpful, please:
- β Star this repository
- π Clap for the Medium article
- π Share with fellow developers
This project is licensed under the MIT License - see the LICENSE file for details.
- The Foundry team for creating an amazing development framework
- The Ethereum development community
- Everyone who contributed feedback and suggestions
- Foundry Book - Official Foundry documentation
- Foundry GitHub - Source code and issues
- Ethereum Smart Contract Best Practices
- Smart Contract Security
Happy Testing! π
Made with β€οΈ for the Ethereum developer community
Last updated: February 2026