This guide covers testing smart contracts in your LazerForge project.
LazerForge is configured to set fixed values for block height and timestamp which ensures that tests run against a predictable blockchain state. This makes debugging easier and guarantees that time or block-dependent logic behaves reliably.
- These values are called by Anvil and when running
forge testso make sure to update theblock_numberandblock_timestampvalues infoundry.toml- Setting these variables correctly is vital when testing against contracts that are live. For example, if the block height is set to some time in August 2024 but you're testing composability with a contract first deployed in October 2024, the test will fail.
- Make sure the values are set for the appropriate network you're testing against!
Tests are handled through test files, written in Solidity and using the naming convention Contract.t.sol.
You can run all of your test files at once:
forge testor specify a certain file, and optionally test:
forge test --match-path test/Contract.t.sol --match-test test_DepositForge can generate gas snapshots for all test functions to see how much gas contracts will consume, or to compare gas usage before and after optimizations.
forge snapshotIf you plan on generating coverage reports, you'll need to install lcov as well.
On macOS, you can do this with the following command:
brew install lcovTo generate reports, run
./coverage-reportTests in LazerForge follow best practices for smart contract testing:
- Use descriptive test names that explain what is being tested
- Use
setUpfunctions to initialize common test state- anything defined in
setUp()is used for the entirety of that test contract
- anything defined in
- Test both positive and negative cases
- Use assertions to verify expected behavior
- Test edge cases and boundary conditions
Example test structure:
contract MyContractTest is Test {
function setUp() public {
// Initialize test state
}
function testPositiveCase() public {
// Test successful execution
}
function testNegativeCase() public {
// Test failure cases
}
}Navigation: