Smart Contract Testing Patterns

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.

Verifying Individual Function Behavior

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"

Composing Multi‑Step Workflows

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

Stress‑Testing Invariants with Fuzzing

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

Measuring What’s Actually Executed with Coverage

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 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

Mocking Oracles and External Dependencies

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

Embedding Tests in CI Pipelines

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

Sharp Edges — What silently fails, confused options, production breakage

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.