STATEFULL AND STATELESS FUZZINGTable-driven testing is used when you want to test a single function with multiple sets of predefined inputs and expected outputs in one go. It’s perfect for functions where you know exactly what the output should be for a given input (e.g., a mathematical operation like addition).
Instead of writing 10 separate unit tests for 10 different input combinations, you define all combinations in a “table” (a struct array) and Foundry runs them all.
As mentioned in the transcript, table-driven testing is a relatively new feature. To use it, you need to install Foundry's nightly (cutting-edge) version, not the stable release.
# Install the nightly version of Foundry
foundryup --nightly
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import "forge-std/Test.sol";
// Define a struct to hold one test case: inputs and expected output.
struct TestCase {
uint256 a;
uint256 b;
uint256 expected;
}
contract TableTest is Test {
// The function under test.
function sum(uint256 x, uint256 y) public pure returns (uint256) {
return x + y;
}
// This function prepares the "table" of test cases.
// The `fixture` keyword tells Foundry to run this before the test.
function testSum_fixture() public pure returns (TestCase[] memory) {
TestCase[] memory tests = new TestCase[](2);
tests[0] = TestCase(1, 2, 3); // 1 + 2 should equal 3
tests[1] = TestCase(10, 20, 30); // 10 + 20 should equal 30
return tests;
}
// The actual test function.
// Foundry will call this once for each entry in the fixture.
function testSum(TestCase memory test) public {
uint256 result = sum(test.a, test.b);
assertEq(result, test.expected); // Check if result matches expectation
}
}
testSum_fixture(): This is not a test itself. It’s a helper function marked with fixture in the function name. Foundry automatically detects this and uses it to generate the data for testSum.