TExcelTAD
Home › Solidity › Testing & Deployment

Testing & Deployment

Because deployed contracts are hard or impossible to change, testing before deployment matters even more than in other software. This lesson gives an overview of the professional workflow: development frameworks, unit tests, test networks and deployment scripts. The framework code below is shown in non-runnable blocks; the testing ideas are demonstrated with runnable Solidity.

The toolchain

Tool What it is
Foundry (forge, cast, anvil) Fast Rust-based toolkit; tests are written in Solidity
Hardhat JavaScript/TypeScript framework; tests usually in TypeScript with ethers.js or viem
Remix Browser IDE, good for quick experiments
anvil / Hardhat Network Local development chains with pre-funded test accounts
Testnets (e.g. Sepolia) Public networks with valueless test ether
Slither, Mythril, Echidna Static analysis, symbolic execution, fuzzing

The account 0xf39F…2266 that this playground uses is the first default test account of Hardhat and anvil, so you'll recognize it later.

Tests in Solidity (Foundry)

A Foundry test is a contract whose functions start with test. setUp() runs before each test, and "cheatcodes" on the vm object control the environment: impersonate an account, set the time, expect a revert.

solidity
// test/Counter.t.sol
import { Test } from "forge-std/Test.sol";
import { Counter } from "../src/Counter.sol";

contract CounterTest is Test {
    Counter counter;

    function setUp() public {
        counter = new Counter();
    }

    function test_IncrementAddsOne() public {
        counter.increment();
        assertEq(counter.count(), 1);
    }

    function test_RevertWhen_NotOwnerResets() public {
        vm.prank(address(0xBAD));            // next call comes from 0xBAD
        vm.expectRevert("not owner");
        counter.reset();
    }

    function testFuzz_IncrementBy(uint8 n) public {   // random inputs, many runs
        for (uint256 i = 0; i < n; i++) counter.increment();
        assertEq(counter.count(), n);
    }
}
bash
forge test -vv            # run all tests with logs
forge test --gas-report   # gas used per function
forge coverage            # which lines were tested

The same idea, runnable here

Without a framework, a test is simply a contract that sets up a scenario, calls functions and checks results. Main can act as a tiny test runner, using try/catch to check expected reverts:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Counter {
    address public owner = msg.sender;
    uint256 public count;

    function increment() external { count += 1; }

    function reset() external {
        require(msg.sender == owner, "not owner");
        count = 0;
    }
}

contract Intruder {
    function reset(Counter c) external { c.reset(); }
}

contract Main {
    uint256 passed;
    uint256 failed;

    function check(bool ok, string memory name) internal {
        if (ok) { passed++; console.log("PASS", name); }
        else { failed++; console.log("FAIL", name); }
    }

    function main() external {
        Counter c = new Counter();
        c.increment();
        check(c.count() == 1, "increment adds one");

        c.increment();
        c.reset();
        check(c.count() == 0, "owner can reset");

        Intruder intruder = new Intruder();
        try intruder.reset(c) {
            check(false, "non-owner reset reverts");
        } catch Error(string memory reason) {
            check(keccak256(bytes(reason)) == keccak256("not owner"), "non-owner reset reverts");
        }

        console.log("passed:", passed, "failed:", failed);
    }
}
PASS increment adds one
PASS owner can reset
PASS non-owner reset reverts
passed: 3 failed: 0

Test the unhappy paths as carefully as the happy ones: who must not be able to call a function, which inputs must revert, what happens at limits (0, maximum values, empty arrays, deadlines exactly at block.timestamp).

Invariant thinking

Beyond single tests, state invariants: properties that must hold after any sequence of calls. For a token: "the sum of all balances equals totalSupply". Fuzzers like Foundry's invariant tests and Echidna call functions in random orders and check them:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Token {
    mapping(address => uint256) public balanceOf;
    uint256 public totalSupply;

    function mint(address to, uint256 v) external { balanceOf[to] += v; totalSupply += v; }

    function transfer(address from, address to, uint256 v) external {
        require(balanceOf[from] >= v, "balance");
        balanceOf[from] -= v;
        balanceOf[to] += v;
    }
}

contract Main {
    function main() external {
        Token t = new Token();
        address[3] memory users = [address(0x1), address(0x2), address(0x3)];
        t.mint(users[0], 100);

        // a deterministic pseudo-random sequence of operations
        uint256 seed = 12345;
        for (uint256 step = 0; step < 50; step++) {
            seed = uint256(keccak256(abi.encode(seed)));
            address from = users[seed % 3];
            address to = users[(seed >> 8) % 3];
            uint256 amount = (seed >> 16) % 40;
            try t.transfer(from, to, amount) {} catch {}
            if (step % 10 == 0) t.mint(to, 5);
        }

        uint256 sum = t.balanceOf(users[0]) + t.balanceOf(users[1]) + t.balanceOf(users[2]);
        console.log("sum of balances:", sum);
        console.log("totalSupply    :", t.totalSupply());
        console.log("invariant holds?", sum == t.totalSupply());
    }
}
sum of balances: 125
totalSupply    : 125
invariant holds? true

Testing from TypeScript (Hardhat)

ts
import { expect } from "chai";
import { ethers } from "hardhat";

describe("Counter", () => {
  it("increments", async () => {
    const counter = await ethers.deployContract("Counter");
    await counter.increment();
    expect(await counter.count()).to.equal(1n);
  });

  it("rejects strangers", async () => {
    const [, stranger] = await ethers.getSigners();
    const counter = await ethers.deployContract("Counter");
    await expect(counter.connect(stranger).reset()).to.be.revertedWith("not owner");
  });
});

Deployment

A deployment is just a transaction whose data is the bytecode plus encoded constructor arguments. Frameworks script it:

solidity
// script/Deploy.s.sol (Foundry)
import { Script } from "forge-std/Script.sol";
import { Counter } from "../src/Counter.sol";

contract Deploy is Script {
    function run() external {
        vm.startBroadcast();          // sign with the key given on the command line
        new Counter();
        vm.stopBroadcast();
    }
}
bash
forge script script/Deploy.s.sol --rpc-url $SEPOLIA_RPC_URL --account deployer --broadcast --verify

A sensible release process:

  1. All tests and static analysis pass; coverage of critical paths is high.
  2. Deploy to a local chain, then a testnet, and try the full user flow there.
  3. Get a review or audit for anything that will hold other people's assets.
  4. Deploy to mainnet from a well-protected key (hardware wallet or multisig), never from a key pasted into a script.
  5. Verify the source code on a block explorer so users can read what they interact with.
  6. Hand admin rights to a multisig/timelock and set up monitoring of events.

Warning: Never commit private keys or seed phrases to a repository, and never reuse a test account's well-known key on a real network: those keys are public, and anything sent to them is taken immediately.

Test yourself

In Foundry, what does vm.prank(addr) do?

  1. Deploys a contract at addr
  2. Makes the next call come from addr as msg.sender
  3. Gives addr ether
  4. Pauses the test

What is an invariant in contract testing?

  1. A variable marked constant
  2. A property that must hold after any sequence of calls
  3. A test that never changes
  4. A gas limit

Why verify the contract source on a block explorer after deploying?

  1. It lowers gas costs
  2. So anyone can check that the deployed bytecode matches the published source
  3. It's needed for the contract to run
  4. It makes the contract upgradeable