forgetest--summaryforgetest-vvvforgetest--match-test<SPECIFIC_TEST_FUNCTION_NAME>forgetest--match-contract<SPECIFIC_CONTRACT_NAME>forgetest--debug<SPECIFIC_TEST_FUNCTION_NAME># h to show/hide help
Tests are written in Solidity. If the test function reverts, the test fails, otherwise it passes.
Test
Description
Unit
Testing a specific part of our code
Integration
Testing how our code works with other parts of our code
Forked
Testing our code on a simulated real environment
Staging
Testing our code in a real environment that is not prod
Fuzz
Testing our code against unexpected/random inputs to find bugs
Writing Tests
DSTest provides basic logging and assertion functionality. To get access to the functions, import forge-std/Test.sol and inherit from Test in your test contract:
import"forge-std/Test.sol";
Example Test Contract
pragmasolidity 0.8.10;import"forge-std/Test.sol";contractContractBTestisTest {uint256 testNumber;stringstring1;stringstring2;// An optional function invoked before each test case is run.functionsetUp() public { testNumber =42;string1= ABC;string2= XYZ; }// Functions prefixed with test are run as a test case.functiontest_NumberIs42() public {assertEq(testNumber,42); }// Inverse test prefix - if the function does not revert, the test fails.functiontestFail_Subtract43() public { testNumber -=43; }functiontest_CompareStrings() public {assertEq(keccak256(abi.encodePacked(string1)),keccak256(abi.encodePacked(string2)) ); }}
Tests are deployed to 0xb4c79daB8f259C7Aee6E5b2Aa729821864227e84. If you deploy a contract within your test, then 0xb4c...7e84 will be its deployer. If the contract deployed within a test gives special permissions to its deployer, such as Ownable.sol's onlyOwner modifier, then the test contract 0xb4c...7e84 will have those permissions.
Test functions must have either external or public visibility. Functions declared as internal or private won't be picked up by Forge, even if they are prefixed with test.
Naming Convention
Shared test setups
If there are multiple tests that all have the same initial setup configuration, use a helper contract to reduce code duplication
To run all tests in a forked environment, such as a forked Ethereum mainnet, pass an RPC URL via the --fork-url flag.
forgetest--fork-url<RPC_URL>
Forking is especially useful when you need to interact with existing contracts. You may choose to do integration testing this way, as if you were on an actual network.