A tutorial that teaches how to test your smart contracts using Foundry.
cheatcodes
that Foundry provides to test your smart contractsforge init hello_foundry_in_base
command provides in the seed Foundry project.
<ContractName>.t.sol
<ContractName>Test
forge-std/Test.sol
.setUp
, which is executed before each test. This is similar to the beforeEach
hook in the Mocha/Typescript world.test
keyword, for instance testIncrement
.vm
instance in your tests. Cheatcodes allow you to perform various tasks, including:
msg.sender
of your tests, and add some console logs via importing the forge-std/console.sol
contract.
The Counter
contract should look as follows:
forge test
, you will see the following:
forge test
command includes a flag that enable you to include more details of the logs emitted during the execution of the tests.
You can control that by including different levels of the verbose flag — -vv
up to -vvvvv
. For more details about the level of verbosity you can refer to the Logs and Traces section of the Foundry documentation.
Run the foundry test -vv
. You should see:
prank
cheatcode, which allow you to modify the msg.sender
of the next transaction. You will also use the addr
cheatcode, which allow you to generate an address using any private key, which can simply be a hex number.
Include some console.log
statements to understand better the execution flow.
The code should look like:
forge test -vv
command, you should see:
vm.prank
before the call to the counter.increment()
and counter.setNumber(x)
functions. This allows you to specify a particular address to become the msg.sender
in the contract. Since the vm.prank
accepts an address, you simply generate an address using the cheatcode vm.addr
, where you pass a simple hexadecimal number, which is a valid private key.