Track 6 · dApps & frontend · lesson 8

Foundry: forge test

14 min


The piggy bank you built in the Track 4 milestone — run its tests on your own machine now. Same contract, same assertions, a terminal instead of a button.

A Foundry project

forge init piggy-bank
cd piggy-bank

That scaffolds src/ for contracts, test/ for tests, and script/ for deployment. Drop your PiggyBank.sol into src/.

Tests are Solidity now

In the Forge, tests were hidden and written for you. In Foundry you write them, and they are themselves Solidity contracts:

// test/PiggyBank.t.sol
import "forge-std/Test.sol";
import "../src/PiggyBank.sol";

contract PiggyBankTest is Test {
    PiggyBank bank;

    function setUp() public {
        bank = new PiggyBank();
    }

    function test_DepositIsCredited() public {
        bank.deposit{value: 1 ether}();
        assertEq(bank.balances(address(this)), 1 ether);
    }

    function test_NonOwnerCannotWithdraw() public {
        vm.prank(address(0xBEEF));       // next call comes from 0xBEEF
        vm.expectRevert();               // and it must revert
        bank.withdraw(1);
    }
}

vm is Foundry's cheat-code interface, and it is why testing in Solidity beats testing from JavaScript. vm.prank sets the next caller. vm.expectRevert asserts a failure. vm.deal hands an address ETH. vm.warp moves time forward.

These are exactly the powers the Forge's hidden test runner had — running a call from a different account, expecting a revert — now in your own hands.

Run them

forge test          # run everything
forge test -vvv     # show traces when something fails
forge test --gas-report   # gas per function

Predict

Why write tests in Solidity rather than in JavaScript with viem?

Choose one answer

Check

What does `vm.prank(addr)` do?

Choose one answer

Worth remembering

  • `forge init` scaffolds src/, test/ and script/; your PiggyBank.sol goes in src/.
  • Foundry tests are Solidity contracts using forge-std's Test base.
  • `vm` cheat codes — prank, expectRevert, deal, warp — are the Forge runner's powers in your hands.
  • `forge test` runs locally and fast; -vvv shows traces, --gas-report shows costs.
  • Solidity tests enable fuzzing: hundreds of random inputs hunting for the breaking case.