Solidity Fuzz Testing
A fuzz test is a test function that takes parameters and is run by the test runner with many different inputs. A property is a rule that must hold for every input the runner tries.
A fuzz test checks addition in either order
The test takes two numbers as parameters. The runner tries many pairs, and every pair must give the same sum in either order.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract Adder {
function add(uint256 a, uint256 b) public pure returns (uint256) {
return a + b;
}
}
Assume keeps doubling inside a safe range
Doubling a very large number would overflow. Assume keeps the input small enough that doubling can never overflow.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract Doubler {
function doubleIt(uint256 x) public pure returns (uint256) {
return x * 2;
}
}
Fixed inputs prove the same property on readable cases
The same addition rule is checked here on three pairs you can read. Fixed cases sit beside a fuzz test as a readable demonstration.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract Adder {
function add(uint256 a, uint256 b) public pure returns (uint256) {
return a + b;
}
}
Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract Calculator {
function add(uint256 a, uint256 b) public pure returns (uint256) {
return a + b;
}
function doubleIt(uint256 x) public pure returns (uint256) {
return x * 2;
}
}
Key points
- Fuzz test: a fuzz test is a test function with parameters that the runner calls with many random inputs.
- Property: a property is a rule the test checks, such as addition giving the same result in either order.
- Random inputs: the runner picks the inputs, so the test covers cases the author did not write by hand.
- Assume: an assume statement skips inputs outside a safe range, such as values that would overflow.
- Use fixed inputs alongside a fuzz test to show the same property on cases you can read.
In this example, a calculator offers addition and doubling. A fuzz test checks that addition commutes, another fuzz test checks that doubling equals adding a number to itself, and a fixed-input test pins down the edge cases of zero and a small value.
Note
a fuzz test proves the property for the inputs the runner tried, not for every possible input.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
What does a fuzz test do?