Writing fuzz tests in Solidity
Hardhat 3 supports fuzz tests in Solidity. These tests run the same function many times with random inputs that Hardhat automatically generates. To create one, write a test function that takes parameters.
Let’s add a fuzz test to our Counter.t.sol file:
5 collapsed lines
// SPDX-License-Identifier: UNLICENSEDpragma solidity ^0.8.28;
import { Counter } from "./Counter.sol";import { Test } from "forge-std/Test.sol";
contract CounterTest is Test {26 collapsed lines
Counter counter;
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(); }
function testFuzz_Inc(uint8 x) public { for (uint8 i = 0; i < x; i++) { counter.inc(); }
require(counter.x() == x, "Value after calling inc x times should be x"); }}When you run your tests, the testFuzz_Inc function will be called multiple times with values that fit in a uint8 (0 to 255). This tests the inc function with a wide range of inputs.
Run your tests again to verify everything passes:
npx hardhat test soliditypnpm hardhat test solidityyarn hardhat test solidity