Skip to content

Using an assertions library

The tests you’ve written so far are simple. They call functions and check that the contract’s state is what you expect. For more complex testing, like checking that the correct event was emitted, you’ll need an assertions library. Solidity doesn’t have a built-in way to do that.

Install the forge-std library, which provides useful testing utilities:

Terminal window
npm add --save-dev "foundry-rs/forge-std#v1.11.0"

Now that it’s installed, modify Counter.t.sol to use forge-std:

contracts/Counter.t.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import { Counter } from "./Counter.sol";
import { Test } from "forge-std/Test.sol";
contract CounterTest {
contract CounterTest is Test {
Counter counter;
17 collapsed lines
function setUp() public {
counter = new Counter();
}
function test_InitialValueIsZero() public view {
require(counter.x() == 0, "x should start at 0");
}
function test_IncIncreasesByOne() public {
counter.inc();
require(counter.x() == 1, "inc should increase x by 1");
}
function test_IncByIncreasesByGivenAmount() public {
counter.incBy(3);
require(counter.x() == 3, "incBy should increase x by the given amount");
}
}

By extending the Test contract, you get access to the assertion library’s functions.

Add a new test that checks the correct event is emitted when you call inc:

contracts/Counter.t.sol
4 collapsed lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import { Counter } from "./Counter.sol";
import { Test } from "forge-std/Test.sol";
contract CounterTest is Test {
Counter counter;
17 collapsed lines
function setUp() public {
counter = new Counter();
}
function test_InitialValueIsZero() public view {
require(counter.x() == 0, "x should start at 0");
}
function test_IncIncreasesByOne() public {
counter.inc();
require(counter.x() == 1, "inc should increase x by 1");
}
function test_IncByIncreasesByGivenAmount() public {
counter.incBy(3);
require(counter.x() == 3, "incBy should increase x by the given amount");
}
function test_IncEmitsIncrementEvent() public {
vm.expectEmit();
emit Counter.Increment(1);
counter.inc();
}
}

The combination of vm.expectEmit() and emit Increment(1); tells the test framework that the next call (counter.inc()) should emit an Increment event with the argument 1. The test will fail if the event isn’t emitted or is emitted with different arguments.

Run the tests again to verify everything works:

Terminal window
npx hardhat test solidity

All tests should pass, including your new event emission test.