Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 47 ยท Security

Testing Contracts

Learn how to test smart contracts: unit tests, fuzzing, invariants, forking and coverage, with Foundry and Hardhat examples and a runnable fuzzing stand-in.

A web app with a bug gets a patch on Tuesday. A contract with a bug may already have lost its users' money by Tuesday, and you often cannot patch it at all. That is why contract developers write far more tests than most programmers, and why the tests go beyond "does it work for the example I thought of".

This lesson covers the kinds of test that matter, what a good test asserts, and how fuzzing and invariants find the bugs you did not imagine. The Foundry and Hardhat code is read-only here, because the site cannot run a node or a compiler. The JavaScript stand-ins run a small test runner and a fuzz loop so you can see the techniques themselves working.

Five kinds of test

Unit One function, one expected result.
Fuzz Random inputs, same property.
Invariant Rules that hold after any sequence.
Fork Run against a copy of a real chain.
1 / 2

Unit tests

A unit test sets up a contract, calls one function and asserts on the result, including the failure cases. For every function ask three questions: what is the normal result, who must be refused, and what are the edge values (0, 1, the maximum, the zero address)?

Foundry tests are written in Solidity itself. Each function starting with test is one test, and setUp runs before each of them:

SOLIDITY
// test/Token.t.sol  (Foundry)
import {Test} from "forge-std/Test.sol";
import {Token} from "../src/Token.sol";

contract TokenTest is Test {
    Token token;
    address alice = makeAddr("alice");
    address bob = makeAddr("bob");

    function setUp() public {
        token = new Token(1_000e18);          // test contract is the deployer
        token.transfer(alice, 100e18);
    }

    function test_TransferMovesBalance() public {
        vm.prank(alice);                      // next call comes from alice
        token.transfer(bob, 40e18);
        assertEq(token.balanceOf(alice), 60e18);
        assertEq(token.balanceOf(bob), 40e18);
    }

    function test_RevertWhen_BalanceTooLow() public {
        vm.prank(alice);
        vm.expectRevert(
            abi.encodeWithSelector(Token.InsufficientBalance.selector, 100e18, 101e18)
        );
        token.transfer(bob, 101e18);
    }
}

vm.prank and vm.expectRevert are cheatcodes, special commands that Foundry's test EVM understands. You run the suite with forge test. The same ideas in Hardhat use JavaScript and ethers (see Talking to Contracts with JavaScript):

JavaScript
// test/token.test.js  (Hardhat with the chai matchers plugin)
const { expect } = require("chai");
const { ethers } = require("hardhat");

describe("Token", () => {
  it("rejects a transfer above the balance", async () => {
    const [owner, alice] = await ethers.getSigners();
    const token = await ethers.deployContract("Token", [1000n]);
    await expect(token.connect(alice).transfer(owner.address, 1n))
      .to.be.revertedWithCustomError(token, "InsufficientBalance");
  });
});

Run it with npx hardhat test. Foundry is usually faster, and Hardhat fits teams that already live in JavaScript. Neither is "better" for learning: the ideas are identical.

What to assert

A weak test says "the call did not revert". A strong test checks the effects:

  • State: balances, owners, counters, flags, before and after.
  • Events: the right event with the right arguments (Events and Logs).
  • Reverts: the specific error, so a different failure cannot make the test pass by accident.
  • Access: every guarded function called by an outsider must fail.
  • Things that must not change: other users' balances, total supply, ownership.

A test runner in thirty lines

The stand-in below is a tiny version of what Foundry and Hardhat do: collect tests, run each in a fresh setup, count passes and failures, and offer a helper to expect a revert. The toy Token is plain JavaScript, not a contract.

JS A mini test runner

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last test is deliberately wrong: it asserts an incorrect sum, so you can see a failure report. A mistake in the test is just as possible as one in the contract, which is a good reason to keep tests short and obvious.

Fuzzing

Hand-written examples only cover cases you thought of. A fuzz test states a property and lets the tool try hundreds of random inputs:

SOLIDITY
function testFuzz_TransferNeverCreatesTokens(uint96 amount) public {
    amount = uint96(bound(amount, 0, 100e18));      // keep inputs in a sensible range
    uint256 before = token.balanceOf(alice) + token.balanceOf(bob);
    vm.prank(alice);
    token.transfer(bob, amount);
    assertEq(token.balanceOf(alice) + token.balanceOf(bob), before);
}

Foundry runs this with many random values of amount (256 by default) and, when one fails, reports the input that broke it. bound squeezes a value into a range; vm.assume(cond) discards inputs that do not fit. Good fuzz properties are statements like "the sum of balances never changes in a transfer" or "withdrawing never pays more than was deposited".

Invariant tests

A unit or fuzz test checks one call. An invariant test checks a rule that must hold after any sequence of calls. The tool calls random functions in random order with random arguments and checks the invariant after every step. In Foundry the invariant is a function whose name starts with invariant:

SOLIDITY
function invariant_TotalSupplyEqualsSumOfBalances() public view {
    assertEq(token.totalSupply(), handler.sumOfBalances());
}

Large projects use a handler contract, which wraps the real contract and records bookkeeping (like the sum of balances) while constraining the random calls to realistic ones. The settings, such as runs and depth (calls per run) live in foundry.toml. Invariants are what catch the bugs between functions: the transfer that works, the burn that works, and the sequence that breaks accounting.

The next stand-in seeds a random generator, throws random operations at a token with a hidden bug, checks the supply invariant after every step and then shrinks the failing sequence to a minimal example, as real fuzzers do.

JS Fuzzing finds the bug, shrinking explains it

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A fuzzer would never need to "know" about self-transfers. It stumbles on one by chance, notices that the total no longer matches, and the shrinker boils the long sequence down to the single call that matters. In real Foundry output you see the same: the call sequence that broke the invariant, reduced to a small one.

Forking and coverage

Some contracts depend on others that already exist on a live network, such as a token, a price feed or an exchange. A fork test runs your tests against a local copy of real chain state fetched from an RPC provider, so you can test an integration without deploying everything yourself:

Terminal
forge test --fork-url $MAINNET_RPC_URL --fork-block-number 20000000

Pinning the block number keeps the test repeatable. Forks are slower and depend on an external service, so use them for integration checks and keep most tests local.

Coverage reports which lines and branches your tests executed: forge coverage in Foundry, npx hardhat coverage with the coverage plugin in Hardhat. It tells you what is untested, never that the tested code is correct. A function can have full line coverage and still be wrong, so use coverage to find gaps, not to prove safety.

Real: the testing techniques and the Foundry/Hardhat commands shown. Stand-in: the runner, the token and the fuzzer are plain JavaScript written for this lesson, and they model the ideas without an EVM or gas.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should a test for a failing call check the specific revert reason or custom error?

    Expecting any revert can hide the wrong failure. Expecting the exact error proves the contract refused for the right reason.
  2. 2. What is an invariant test?

    The tool calls functions in random order with random arguments and checks the rule, such as supply equals the sum of balances, after every step.
  3. 3. What does shrinking do after a fuzzer finds a failing input or sequence?

    A shrunk counterexample removes noise, making it much easier to see which call actually breaks the property.
  4. 4. A suite has 100% line coverage. What can you conclude?

    Coverage shows what was executed, not whether the assertions were meaningful or complete.

Summary

  • Test failure cases and permissions as carefully as success cases, and assert on state, events and the exact revert error.
  • Unit tests cover the cases you imagine; fuzz tests check a property over many random inputs.
  • Invariant tests check rules across random call sequences and find bugs that live between functions.
  • Fork tests run against real chain state for integrations; pin the block for repeatability.
  • Coverage finds gaps, it does not prove correctness.

Next: Audits, Tools and Best Practices.