Comprehensive guide for smart contract testing patterns covering essential concepts, practical examples, and production best practices.
Smart contract testing patterns are repeatable, automated ways to validate EVM bytecode behavior before deployment. They matter whenever code moves from local development to testnet or mainnet, especially when value, state mutations, or permission changes are involved. This page maps the patterns engineers actually use to accomplish specific verification goals, with concrete commands, exact flag syntax, and the real error text you'll encounter when a pattern fails.
When the goal is to confirm that a single function returns the expected value or reverts with a specific reason, the standard pattern is a Foundry test function named function test<DescriptiveName>(). Foundry makes vm cheatcodes available automatically inside any test, so you can set signers, advance block time, and assert state.
Test code
// test/Token.t.sol
function testTransferSuccess() public {
address recipient = makeAddr(1);
uint256 amount = 10 * 10 ** uint256(token.decimals());
vm.prank(deployer);
token.transfer(recipient, amount);
assertEq(token.balanceOf(recipient), amount);
}
Command
forge test --mt testTransferSuccess
Expected output (success)
Ran 1 test in 0.02s OK
Expected output (assertion failure)
RAN 1 TEST IN 0.02s FAILED testTransferSuccess (revert)
If the transaction reverts without a caught reason
Panic: 0x0 ... revert: ERC20: transfer amount exceeds balance
Matched‑revert pattern with vm.expectRevert
function testRevertOnZeroBalance() public {
vm.expectRevert("ERC20: transfer amount exceeds balance");
token.transfer(address(0), 1e20);
}
Running forge test --mt testRevertOnZeroBalance produces:
testRevertOnZeroBalance (call:0x...): expected revert matched
If the revert reason differs by even a single character:
revert: expected "ERC20: transfer amount exceeds balance" but got "ERC20: insufficient allowance"
When a test requires deploying a contract, calling a sequence of functions, and verifying final state—or simulating a user journey across several contracts—the most maintainable pattern is a Foundry script rather than a single test function. Scripts are compiled Solidity that run via forge script and can use cheatcodes just like tests.
Script skeleton
// script/DeployAndInteract.s.sol
#![allow(unused_imports)]
#![allow(clippy::empty_pragma_block)]
import {Script} from "forge-std/Script.sol";
contract DeployAndInteract is Script {
function run() external {
address deployer = vm.accounts(0);
Bank bank = new Bank();
address recipient = makeAddr(1);
uint256 amt = 100e18;
vm.prank(deployer);
bank.deposit{value}(amt);
uint256 stored = bank.balanceOf(recipient);
if (stored != amt) {
revert "balance mismatch after deposit";
}
bank.withdraw(amt);
uint256 remaining = bank.balance(deployer);
if (remaining != 0) {
revert "withdrawal left residual";
}
}
}
Command
forge script script/DeployAndInteract.s.sol --rpc-url http://localhost:8545 --private-key 0xac0974bec39a17e36ba4a6b4d238ff944bac40f8c4b2c661c13945d13b4a1e8f5
Ad‑hoc state query with cast After a deployment, you often need a quick read to confirm state before proceeding:
cast call --rpc-url http://localhost:8545 0xYourBankContract "balanceOf(address)(uint256)" 0xRecipient
Expected output
100000000000000000000
If the contract reverts on a read‑only call (e.g., a getter that isn’t view)
Error: failed to make call: transaction would fail; consider using --send
If the address is wrong or contract not deployed
Error: invalid address or contract not deployed at that location
When the goal is to discover inputs that break an invariant—such as a mathematical property, access‑control edge case, or overflow condition—property‑based fuzzing generates random inputs and checks whether the contract state remains consistent. Foundry’s fuzzer integrates directly into the test suite via the #[fuzz] modifier or forge fuzz CLI.
Fuzz test pattern
// test/Invariant.t.sol
function transferAndBalanceFuzz(address a, address b, uint256 amount) external fuzz {
vm.prank(a);
uint256 beforeA = token.balanceOf(a);
token.transfer(b, amount);
uint256 afterA = token.balanceOf(a);
if (afterA != beforeA - amount) {
revert "invariant broken: balance delta mismatch";
}
}
Command
forge fuzz --fuzz-runs 5000 --contracts-dir .
Typical output when an invariant breaks
🛑 Counterexample found after 1,234 steps:
a = 0x1111111111111111111111111111111111111111
b = 0x2222222222222222222222222222222222222222
amount = 0
gas used: 42,317
When the fuzzer runs the full budget without hitting a violation:
✅ 5,000 fuzz iterations completed; no counterexample found.
gas avg: 12.3k
Sharp edges specific to fuzzing
vm.createSelectAccount().--fuzz-runs values on contracts with high‑cost operations can cause the fuzzer to abort with Out of gas before reaching the target count. Cap the run size per contract complexity, or use --fuzz-amount to limit value ranges.vm.expectRevert, the fuzzer may count it as a success or silently skip it. Pair fuzz tests with explicit revert expectations when testing error paths.Knowing which lines of Solidity were touched during testing prevents blind spots. Foundry’s coverage pass instruments bytecode during forge test and emits a report you can browse or fail CI on.
Command
forge coverage
What it produces
coverage.json machine‑readable summary per contract.coverage/ directory with an HTML tree where gray = uncovered, green = executed, red = executed but reverted. ==== Coverage Summary ====
Contract Files Lines Branches Functions Modifiers
Bank 1 47 58 8 3
uncovered lines: 12, 23, 35
If you run coverage without any tests
No coverage data collected. Run forge test first, then forge coverage.
Sharp edges
forge test executions. Running forge script, cast call, or manual anvil interactions does not instrument bytecode, so those paths stay gray even if they’re critical production flows.abigen), the granularity can make it hard to spot which hand‑written logic is untested.forge coverage respects --mt and --match-test filters, so you can generate coverage for a subset of tests and then iterate, but you must rerun the full suite for a complete report.Smart contracts almost always depend on external inputs—price feeds, randomness beacons, governance timers. Testing these in isolation requires replacing the real contract with a deterministic mock that you control. Foundry makes this painless via vm.mockOracle (for USDC‑style mocks) or by deploying a stub contract alongside the system under test.
Mock pattern using a stub contract
// test/OracleMock.sol
contract OracleMock is Test {
address public ethUsdPrice;
function setPrice(uint256 price) external {
ethUsdPrice = price;
}
function latestAnswer() external view returns (uint256) {
return ethUsdPrice;
}
}
In the contract under test, the oracle interface is abstract; at test time you vm.mockOracle(OracleMock) or simply deploy the mock and pass its address to the system under test.
Command to run a test that uses a mock
forge test --mt testPriceImpactWithMock
Expected output (success)
Ran 1 test in 0.03s OK
If the mock is not deployed or the address mismatches
Error: could not find contract at 0x... (no code found)
If the contract reverts because the mock returns a zero price and the system under test requires a non‑zero value
revert: Price out of range
Sharp edges
vm.mockOracle only works for contracts that inherit from Consul‑style interfaces or use the oracle cheatcode pattern; if the target contract calls aggregator.latestAnswer() directly without an intermediate mockable wrapper, you’ll need to deploy a true stub and inject its address via constructor arguments or vm.prank.setPrice(2000) and the next test expects the default, the default may be 0 or stale, leading to flaky failures. Always reset mock state in setUp() or use separate mock deployments per test.TimeoutError: RPC endpoint did not respond within 10s when your CI runner cannot reach the external feed. Pin oracle addresses to environment variables and prefer local mocks in CI.The most common pattern is to invoke Foundry’s test suite from a CI step and fail the job if any test reverts or coverage drops below a threshold.
GitHub Actions example
name: Foundry Tests
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Foundry
uses: foundry-rs/foundry-toolchain@v1
with:
version: nightly
- name: Install dependencies
run: foundryup
- name: Run tests
run: forge test --coveragereport html
- name: Upload coverage report
uses: actions/upload-artifact@v4
with:
name: coverage-report
path: coverage/
Docker‑only fallback (no CI runner with Foundry pre‑installed)
docker run --rm -v "$PWD":/workspace -w /workspace foundry-rs/foundry forge test
Sharp edges in CI
~/.foundry. If a base image layer changes (e.g., OS updates) but the cache persists, you may see stale contract ABIs reflected in test output. Pin the foundry-toolchain version or add foundryup to your Dockerfile.429 Too Many Requests. Pin testnets or use anvil/local nodes in CI.--coveragereport html flag generates the HTML tree; without it, forge coverage still writes coverage.json but the step that uploads coverage/ as an artifact will have nothing to show.vm.prank and vm.warp persist across test* functions. If a test deposits ETH or mints tokens, the next test starts from that augmented state. Fix: use setUp() to deploy fresh contracts, or vm.reset() at the top of each test (available in newer Foundry versions).--mt vs --match-test confusion: Both flags filter test names, but --mt is the canonical short form. --match-test is an alias that some newcomers type out of habit; using both on the same line causes forge to error: unknown option --match-test if --mt is also present, or silently apply the last one. Stick to one form per invocation.revert: MaxUsersExceeded not because of the target logic but because of accumulated state. Always vm.createSelectAccount() or similar reset, or run fuzz on a stateless contract.forge script and cast call do not instrument coverage. If your CI only runs forge coverage after forge script steps that exercise critical paths, those paths will appear uncovered and may block merges unnecessarily, or worse, go unreported if you forget the coverage step.vm.expectRevert("some error") does an exact string match on the revert reason. If the contract upgrades its error wording (e.g., from InsufficientFunds to ERC20: insufficient funds), the test will fail with expected revert but got different reason, even though the behavior is correct. Prefer matching on error codes (require(false, 0x...)) or substring checks if the platform supports it.block.timestamp to test timelocks or vesting schedules. In production, block.timestamp is set by the consensus layer and can drift relative to local test time. If your contract uses block.timestamp for access control and you haven't accounted for clock skew, a deployment that passes local tests may revert under real‑world timing. Prefer block.number-based checks or explicit pause mechanisms rather than pure timestamp arithmetic.This page was rewritten on 18 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy