SolidityIn

Testing reverts, events and cheatcodes

Lesson 28 of 40 · Testing

Good tests check failures as well as success. The cheatcode vm.expectRevert tells Foundry that the next call must revert, and it can check the exact error message or custom error.

Cheatcodes are special functions on the vm object that change the test environment. vm.prank makes the next call come from another address, vm.deal gives an address ETH, and vm.warp moves the clock forward, which is how you test deadlines like the one in the crowdfunding contract.

To test events, call vm.expectEmit, then emit the event you expect, then make the real call. The test fails if the contract does not emit a matching event.

Aim to test every require and every branch. Run forge coverage to see which lines your tests never reach, and forge snapshot to track gas changes over time.

contract VaultTest is Test {
    Vault v;
    address alice = address(0xA11CE);
    event Deposited(address indexed who, uint256 amount);

    function setUp() public {
        v = new Vault();
        vm.deal(alice, 10 ether);
    }
    function test_RevertWhenNotOwner() public {
        vm.prank(alice);
        vm.expectRevert("Not owner");
        v.withdrawAll();
    }
    function test_EmitsDeposit() public {
        vm.expectEmit(true, false, false, true);
        emit Deposited(alice, 1 ether);
        vm.prank(alice);
        v.deposit{value: 1 ether}();
    }
}

Try it yourself

Write a test for the Crowdfund contract: use vm.warp to jump past the deadline, and check that refund works when the goal was not met.

Quick check: Which cheatcode moves the blockchain clock forward?