Smart Contract Testing Tools Compared

Foundry, Hardhat 3, Echidna and Medusa compared for unit, fuzz and invariant testing of Solidity contracts, with working test examples for each.

In this guide
  1. The kinds of tests you need
  2. Foundry
  3. Hardhat 3
  4. Dedicated fuzzers: Echidna and Medusa
  5. Side-by-side comparison
  6. A workable testing routine
  7. FAQ
  8. Sources

For Solidity projects in late 2026, the practical choice is between Foundry and Hardhat 3, and many teams use ideas from both. Foundry runs tests written in Solidity and has the most mature fuzzing and invariant tooling. Hardhat 3 now runs Foundry-compatible Solidity tests too, and adds TypeScript tests for end-to-end flows. Dedicated fuzzers such as Echidna and Medusa go deeper when a protocol holds real value.

The examples below were checked against Foundry v1.8 and Hardhat 3.24.

The kinds of tests you need

Deployed contracts are hard or impossible to patch, so testing carries more weight than in ordinary web development. A reasonable suite has four layers:

Layer Question it answers Typical tool
Unit tests Does this function do what it should for a known input? Solidity tests in Foundry or Hardhat
Fuzz tests Does it hold for random inputs? Foundry or Hardhat Solidity tests
Invariant tests Does a property hold after any sequence of calls? Foundry, Hardhat, Echidna, Medusa
Integration and fork tests Does the whole flow work with other contracts and off-chain code? Hardhat TypeScript tests, Foundry fork tests

Tests reduce risk but do not replace review. Many common smart contract audit findings are logic errors that only a targeted invariant, or a human reader, will catch.

All examples use this small contract:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

contract Vault {
    mapping(address => uint256) public balanceOf;
    uint256 public totalDeposits;

    function deposit() external payable {
        balanceOf[msg.sender] += msg.value;
        totalDeposits += msg.value;
    }

    function withdraw(uint256 amount) external {
        require(balanceOf[msg.sender] >= amount, "insufficient balance");
        balanceOf[msg.sender] -= amount;
        totalDeposits -= amount;
        (bool ok, ) = msg.sender.call{value: amount}("");
        require(ok, "transfer failed");
    }
}

Foundry

Foundry is a Rust toolchain: forge builds and tests, anvil is a local node, and cast is a command-line RPC client. The latest stable release at the time of writing is v1.10.1, published in November 2026.

Tests are Solidity contracts. Any function whose name starts with test is a test, and a test fails if it reverts. "Cheatcodes" on the vm object manipulate the environment: set the caller, change balances, move time, expect a revert.

// test/Vault.t.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

import {Test} from "forge-std/Test.sol";
import {Vault} from "../src/Vault.sol";

contract VaultTest is Test {
    Vault vault;
    address alice = makeAddr("alice");

    function setUp() public {
        vault = new Vault();
        vm.deal(alice, 100 ether);
    }

    function test_DepositUpdatesBalance() public {
        vm.prank(alice);
        vault.deposit{value: 1 ether}();
        assertEq(vault.balanceOf(alice), 1 ether);
    }

    function test_RevertWhen_WithdrawingTooMuch() public {
        vm.expectRevert("insufficient balance");
        vm.prank(alice);
        vault.withdraw(1 ether);
    }

    function testFuzz_DepositThenWithdraw(uint256 amount) public {
        amount = bound(amount, 1, 100 ether);
        vm.startPrank(alice);
        vault.deposit{value: amount}();
        vault.withdraw(amount);
        vm.stopPrank();

        assertEq(vault.balanceOf(alice), 0);
        assertEq(alice.balance, 100 ether);
    }
}
forge test                 # run everything
forge test --mt testFuzz -vvv   # filter by test name, show traces
forge coverage             # coverage report

Fuzz tests

The third test takes a parameter, and that is all it takes for Forge to fuzz it. Forge generates random inputs and runs the function 256 times by default. bound maps any input into a valid range; the alternative, vm.assume, discards inputs that fail a condition and wastes runs if the condition is rarely true.

# foundry.toml
[fuzz]
runs = 1000

[invariant]
runs = 256
depth = 100
fail_on_revert = false

When a fuzz test fails, Forge reports the seed. Re-run with --fuzz-seed to reproduce it.

Invariant tests

An invariant test states something that must be true no matter what users do. Forge calls random functions in random order and checks every invariant_ function along the way. Pointing the fuzzer at a handler contract, rather than the raw target, keeps inputs realistic.

// test/Vault.invariant.t.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

import {Test} from "forge-std/Test.sol";
import {Vault} from "../src/Vault.sol";

contract VaultHandler is Test {
    Vault public vault;

    constructor(Vault _vault) {
        vault = _vault;
    }

    function deposit(uint256 amount) external {
        amount = bound(amount, 0, 10 ether);
        vm.deal(address(this), amount);
        vault.deposit{value: amount}();
    }

    function withdraw(uint256 amount) external {
        amount = bound(amount, 0, vault.balanceOf(address(this)));
        vault.withdraw(amount);
    }

    receive() external payable {}
}

contract VaultInvariantTest is Test {
    Vault vault;
    VaultHandler handler;

    function setUp() public {
        vault = new Vault();
        handler = new VaultHandler(vault);
        targetContract(address(handler));
    }

    function invariant_BalanceMatchesDeposits() public view {
        assertEq(address(vault).balance, vault.totalDeposits());
    }
}

The property here, "the ETH held equals the recorded deposits", is the sort of accounting rule that breaks under reentrancy or rounding bugs. Writing such properties also comes up in blockchain developer interview questions.

Hardhat 3

Hardhat 3 is a substantial redesign of the JavaScript-based toolchain. Its documentation lists Node.js 22.13 or later as a requirement, and configuration files use ES modules. A new project is created with:

mkdir vault-project && cd vault-project
npx hardhat --init

Hardhat 3 supports two kinds of tests in the same project.

Solidity tests

Hardhat's Solidity tests are compatible with Foundry-style tests, including fuzz and invariant tests and many cheatcodes. A file is treated as a test if it sits under contracts/ and ends in .t.sol, or lives in the configured Solidity test directory. The default project template includes forge-std, so the VaultTest contract above runs with only the import path of Vault.sol adjusted.

The documentation lists differences from Foundry that matter when sharing tests between the two:

  • test configuration cannot be set through inline NatSpec comments;
  • scripting cheatcodes such as startBroadcast are not supported;
  • getCode and getDeployedCode cheatcodes are not supported;
  • legacy testFail-prefixed tests are off by default; use vm.expectRevert.

TypeScript tests

TypeScript tests run against a simulated chain from Node.js. Hardhat's docs recommend them for multi-step scenarios across accounts and blocks and for checking integration with off-chain code. The test runner is pluggable; the default template pairs Node's built-in node:test runner with viem.

// test/Vault.ts
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { network } from "hardhat";
import { parseEther } from "viem";

describe("Vault", async function () {
  const { viem } = await network.create();
  const publicClient = await viem.getPublicClient();
  const [alice] = await viem.getWalletClients();

  it("tracks a deposit and pays it back", async function () {
    const vault = await viem.deployContract("Vault");

    await vault.write.deposit({
      value: parseEther("1"),
      account: alice.account,
    });
    assert.equal(
      await vault.read.balanceOf([alice.account.address]),
      parseEther("1"),
    );

    await vault.write.withdraw([parseEther("1")], { account: alice.account });
    assert.equal(await publicClient.getBalance({ address: vault.address }), 0n);
  });

  it("rejects withdrawals above the balance", async function () {
    const vault = await viem.deployContract("Vault");

    await viem.assertions.revertWith(
      vault.write.withdraw([1n]),
      "insufficient balance",
    );
  });
});
npx hardhat test            # all tests
npx hardhat test solidity   # only Solidity tests
npx hardhat test nodejs     # only node:test tests
npx hardhat test --coverage # with built-in coverage

The contract object returned by viem.deployContract is typed from the compiled ABI, so a wrong argument type fails at compile time. A front end uses the same viem API, as shown in our wallet integration guide. A Mocha and ethers.js template is also available.

Other Hardhat 3 features relevant to testing: built-in coverage for both test types, build profiles for separate development and production compiler settings, and simulated networks with a chain type, including an OP Stack mode for rollup-specific behavior. Hardhat 2 still receives fixes but is scheduled to reach end of life by June 2027 at the latest, so new projects should start on version 3.

Dedicated fuzzers: Echidna and Medusa

Both come from the security firm Trail of Bits and are published under its Crytic GitHub organization.

  • Echidna is a Haskell program for property-based fuzzing of Ethereum contracts. In its default mode you write functions prefixed echidna_ that take no arguments and return a boolean; Echidna tries to find a call sequence that makes one return false. It also has assertion and optimization modes, among others.
  • Medusa is a newer fuzzer from the same team, written in Go and introduced as a faster, more scalable alternative.

These tools focus entirely on exploring call sequences and are typically run as long, dedicated jobs rather than on every commit. They are worth adding once a protocol manages funds; a learning project can stay with Forge invariants.

Side-by-side comparison

Foundry Hardhat 3 Echidna / Medusa
Test language Solidity Solidity and TypeScript Solidity properties
Runtime needed Standalone binaries Node.js 22.13+ Standalone binaries
Fuzz and invariant tests Yes, with extensive configuration Yes, Foundry-compatible Core purpose
End-to-end tests with client libraries Not the focus Yes, with viem or ethers.js No
Coverage forge coverage --coverage flag Coverage-guided internally
Local node anvil npx hardhat node Not applicable
Deployment tooling Solidity scripts Hardhat Ignition modules Not applicable

Which to pick

  • Contract-focused work, security emphasis, or a team fluent in Solidity: Foundry.
  • Full-stack dApp where the same team writes contracts and TypeScript: Hardhat 3, using Solidity tests for units and TypeScript for flows.
  • Coming from web development: Hardhat's TypeScript tests feel familiar, but learn Solidity tests early. They are the common language of both tools. See our path for web developers moving to blockchain.
  • Protocol holding user funds: either framework plus a dedicated fuzzing campaign and an external audit.

A workable testing routine

  1. Write a unit test for each external function's happy path and each revert reason.
  2. Turn any test with a hard-coded number into a fuzz test with bound.
  3. List the properties that must always hold (accounting sums, access rules, supply caps) and encode each as an invariant.
  4. Add integration tests for flows that span several contracts or depend on events your indexer consumes.
  5. Run unit and fuzz tests on every push; run long invariant or fuzzer campaigns on a schedule.
  6. When a bug is found, add a regression test before fixing it.

Coverage shows which lines ran, not whether the assertions were meaningful. A passing suite only rules out the bugs you thought to look for, which is why audits remain standard practice; see smart contract security basics.

FAQ

Can I use Foundry and Hardhat in the same repository?

Yes. Solidity tests based on forge-std are compatible with both, subject to the differences listed above, so some teams run unit tests with either tool and keep TypeScript integration tests in Hardhat.

Do I need to know TypeScript to test contracts?

No. Solidity tests cover unit, fuzz and invariant testing without any JavaScript. TypeScript becomes useful for end-to-end scenarios and for sharing code with a front end.

How many fuzz runs are enough?

There is no universal number. Forge's default of 256 runs per test suits every commit. Raise it for scheduled jobs, and rely on invariant tests and dedicated fuzzers for deeper exploration.

Sources

About the author

Alessandro Moretti is a crypto analyst and blockchain strategist who writes and maintains the guides on BlockDev Path. Every factual claim is checked against the primary sources listed above. Spotted an error? Tell us and we will correct it. See our editorial policy.