Testing with Foundry
Tests are not optional for smart contracts, because deployed code cannot be patched and bugs can cost real money. Foundry is a fast toolkit where you write tests in Solidity itself, so there is no new language to learn.
Install it with foundryup, then run forge init to create a project. Tests live in the test folder, and each test function name starts with test. Foundry runs a function called setUp before every test, which gives each test a fresh contract.
Use assertEq, assertTrue and similar helpers to check results. Run everything with forge test, and add -vvv to see detailed traces when something fails.
Fuzz tests are a strong feature. If a test function takes parameters, Foundry runs it with hundreds of random inputs, which finds edge cases that you would not think to write by hand. The example assumes the Counter from the first lesson with the setCount function from its exercise.
// test/Counter.t.sol import "forge-std/Test.sol"; import "../src/Counter.sol"; contract CounterTest is Test { Counter c; function setUp() public { c = new Counter(); } function test_Increment() public { c.increment(); assertEq(c.count(), 1); } function testFuzz_SetCount(uint256 x) public { c.setCount(x); assertEq(c.count(), x); } }
Try it yourself
On your computer, install Foundry, run forge init, copy the Counter contract into src, add this test and run forge test.