# Writing fuzz tests in Solidity

Description: Hardhat 3 Tutorial - Writing fuzz tests in Solidity

Note: This document was authored using MDX

  Source: https://github.com/NomicFoundation/hardhat-website/tree/main/src/content/docs/docs/tutorial/fuzz-tests.mdx

  Components used in this page:
    - <Run cmd="..."/>: Runs a command in the terminal with npm/pnpm/yarn.
    - collapse={X-Y}: Collapses line ranges in code blocks. Supports multiple ranges: `collapse={1-5, 12-14}`.

import Install from "@hh/Install.astro";
import Run from "@hh/Run.astro";

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:

```solidity collapse={1-6,9-34} ins={36-42}
// 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 is Test {
  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:

<Run command="hardhat test solidity" />
