🎓 A1Learner
🔍
0 of 48 lessons completed

Solidity Foundry Unit Tests

A Foundry unit test is a function in a test contract that checks one behaviour of a contract with plain require statements. The test runner runs each test function on a fresh local chain and reports a pass or a fail for each one.

setUp prepares a fresh counter for every test

setUp creates a new counter before each test. Both tests below start from zero, even though one of them changes the count.

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

contract Counter {
    uint256 public count;

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

A test checks a stored value with require

The test stores a score and requires the stored value back. A wrong value would fail the test instead of passing it.

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

contract ScoreBoard {
    uint256 public score;

    function setScore(uint256 newScore) public {
        score = newScore;
    }
}

One test cannot change another test's starting point

The first test increments the counter to one. The second test still starts at zero because setUp runs again before it.

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

contract Counter {
    uint256 public count;

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

Example

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

contract ScoreKeeper {
    uint256 public score;

    function increment() public {
        score += 1;
    }

    function addPoints(uint256 points) public {
        score += points;
    }

    function reset() public {
        score = 0;
    }
}

Key points

  • Test function: a test function is a function whose name starts with test and checks one behaviour.
  • Require check: a require statement inside a test fails the test when its condition is false.
  • setUp: a setUp function runs before each test and prepares fresh state for it.
  • Fresh state: each test starts from the setUp state, so one test cannot change another test's starting point.
  • Use a test name that states the claim it proves, so the pass line reads as evidence.

In this example, setUp creates a fresh score keeper before each test. One test increments, one adds points, and one resets after adding, and each test proves its claim with require statements.

Note

test functions run on a local test chain, never on a live network.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Remix IDE

Exercise

What does setUp do in a test contract?