Smart Contract Testing Strategies
Overview
Smart contract testing is critical due to the immutable and financial nature of blockchain applications. A comprehensive testing strategy combines multiple approaches to catch different types of bugs.
β οΈ
Smart contracts handle real money. Thorough testing is not optionalβit's a requirement. The cost of testing is always less than the cost of exploitation.
Testing Pyramid
Testing Types
Unit Testing
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "../src/Token.sol";
contract TokenUnitTest is Test {
Token public token;
address public owner = address(0x1);
address public user1 = address(0x2);
address public user2 = address(0x3);
function setUp() public {
vm.prank(owner);
token = new Token("TestToken", "TT", 18);
vm.prank(owner);
token.mint(owner, 1000 ether);
}
// Test: Initial state
function testInitialState() public view {
assertEq(token.name(), "TestToken");
assertEq(token.symbol(), "TT");
assertEq(token.decimals(), 18);
assertEq(token.totalSupply(), 1000 ether);
assertEq(token.balanceOf(owner), 1000 ether);
}
// Test: Transfer success
function testTransferSuccess() public {
vm.prank(owner);
token.transfer(user1, 100 ether);
assertEq(token.balanceOf(user1), 100 ether);
assertEq(token.balanceOf(owner), 900 ether);
}
// Test: Transfer failure - insufficient balance
function testTransferInsufficientBalance() public {
vm.prank(user1);
vm.expectRevert("ERC20: insufficient balance");
token.transfer(user2, 100 ether);
}
// Test: Transfer failure - zero address
function testTransferToZeroAddress() public {
vm.prank(owner);
vm.expectRevert("ERC20: transfer to zero address");
token.transfer(address(0), 100 ether);
}
// Test: Approve and transferFrom
function testApproveAndTransferFrom() public {
vm.prank(owner);
token.approve(user1, 200 ether);
assertEq(token.allowance(owner, user1), 200 ether);
vm.prank(user1);
token.transferFrom(owner, user2, 150 ether);
assertEq(token.balanceOf(user2), 150 ether);
assertEq(token.allowance(owner, user1), 50 ether);
}
// Test: Events
function testTransferEvent() public {
vm.prank(owner);
vm.expectEmit(true, true, false, true);
emit Transfer(owner, user1, 100 ether);
token.transfer(user1, 100 ether);
}
// Test: Multiple transfers
function testMultipleTransfers() public {
vm.startPrank(owner);
token.transfer(user1, 100 ether);
token.transfer(user2, 200 ether);
vm.stopPrank();
assertEq(token.balanceOf(user1), 100 ether);
assertEq(token.balanceOf(user2), 200 ether);
assertEq(token.balanceOf(owner), 700 ether);
}
}
Unit Test Coverage Metrics
| Metric | Target | Description |
|---|---|---|
| Line Coverage | >95% | Lines executed |
| Branch Coverage | >90% | Branches taken |
| Function Coverage | 100% | Functions called |
| Statement Coverage | >95% | Statements executed |
Integration Testing
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "../src/Token.sol";
import "../src/Vault.sol";
import "../src/UniswapRouter.sol";
contract IntegrationTest is Test {
Token public token;
Vault public vault;
UniswapRouter public router;
address public owner = address(0x1);
address public user = address(0x2);
function setUp() public {
// Deploy contracts
vm.startPrank(owner);
token = new Token("TestToken", "TT", 18);
vault = new Vault(address(token));
// Setup liquidity
token.mint(owner, 10000 ether);
token.approve(address(vault), type(uint256).max);
vault.deposit(1000 ether);
vm.stopPrank();
// Fund user
vm.prank(owner);
token.transfer(user, 1000 ether);
}
// Test: Deposit and withdraw flow
function testDepositWithdrawFlow() public {
// User deposits
vm.startPrank(user);
token.approve(address(vault), 100 ether);
vault.deposit(100 ether);
// Check vault shares
uint256 shares = vault.balanceOf(user);
assertTrue(shares > 0);
// User withdraws
vault.withdraw(shares);
vm.stopPrank();
// Verify final state
assertGt(token.balanceOf(user), 900 ether); // Slight gain from fees
}
// Test: Multi-step DeFi interaction
function testDeFiIntegration() public {
vm.startPrank(user);
// Step 1: Approve
token.approve(address(vault), 500 ether);
// Step 2: Deposit
vault.deposit(500 ether);
// Step 3: Claim rewards
vm.warp(block.timestamp + 7 days);
vault.claimRewards();
// Step 4: Withdraw
uint256 shares = vault.balanceOf(user);
vault.withdraw(shares);
vm.stopPrank();
// Verify user received rewards
assertGt(token.balanceOf(user), 500 ether);
}
// Test: Error handling in integration
function testIntegrationErrorHandling() public {
vm.startPrank(user);
// Approve but not enough
token.approve(address(vault), 50 ether);
// Try to deposit more than approved
vm.expectRevert("ERC20: insufficient allowance");
vault.deposit(100 ether);
vm.stopPrank();
}
}
Fork Testing
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
contract ForkTest is Test {
// Fork mainnet at specific block
function setUp() public {
vm.createSelectFork("mainnet", 18000000);
}
// Test against real Uniswap
function testUniswapSwap() public {
address router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D";
address weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
address usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";
// Get real balances
uint256 wethBalance = IERC20(weth).balanceOf(address(this));
uint256 usdcBalance = IERC20(usdc).balanceOf(address(this));
// Perform real swap
IUniswapV2Router routerInstance = IUniswapV2Router(router);
uint256 amountIn = 1 ether;
uint256[] memory amounts = routerInstance.getAmountsOut(amountIn, path);
// Verify against real protocol
assertGt(amounts[1], 0);
}
// Test Aave lending
function testAaveDeposit() public {
address aavePool = 0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9";
address dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F";
// Deposit real DAI to Aave
IERC20(dai).approve(aavePool, 1000 ether);
IAavePool(aavePool).deposit(dai, 1000 ether, address(this), 0);
// Verify aToken received
uint256 aTokenBalance = IERC20(aDai).balanceOf(address(this));
assertEq(aTokenBalance, 1000 ether);
}
// Fuzz test against real protocol
function testFuzzUniswap(uint256 amountIn) public {
vm.assume(amountIn > 0 && amountIn <= 100 ether);
// Test with random amounts
// ... implementation
}
}
Fork Testing Benefits
| Benefit | Description | Example |
|---|---|---|
| Real State | Actual mainnet data | Test against real TVL |
| Protocol Integration | Real DeFi interactions | Uniswap, Aave, Compound |
| No Deployment | Skip testnet deploy | Quick testing |
| Reproducible | Pin block number | Consistent results |
Formal Verification
What is Formal Verification?
Certora Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "../src/Token.sol";
contract TokenVerification is Test {
Token public token;
function setUp() public {
token = new Token("Test", "TST", 18);
}
// Formal verification specification
// Total supply invariant: sum(all balances) == totalSupply
function invariant_totalSupplyConsistency() public view {
uint256 calculatedTotal = 0;
// In actual Certora, this would be symbolic
// This is a simplified example
require(
token.totalSupply() == calculatedTotal,
"Total supply invariant broken"
);
}
// No overflow invariant
function invariant_noOverflow() public {
// Verify no overflow in critical operations
uint256 a = type(uint256).max - 1;
uint256 b = 2;
// Should revert, not overflow
vm.expectRevert();
unchecked {
uint256 result = a + b;
}
}
}
Certora CVL Specification
// spec/Token.spec
// Rules
rule totalSupplyIsSumOfBalances() {
uint256 totalBefore = token.totalSupply();
// Any transfer should preserve total supply
env e;
address from;
address to;
uint256 amount;
token.transfer(e, from, to, amount);
uint256 totalAfter = token.totalSupply();
assert totalBefore == totalAfter,
"Total supply changed after transfer";
}
// No overflow
rule noOverflow() {
env e;
address from;
address to;
uint256 amount;
require balanceOf[from] >= amount;
token.transfer(e, from, to, amount);
assert balanceOf[from] + balanceOf[to] <= max_uint256,
"Overflow occurred";
}
Fuzz Testing
Property-Based Testing
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "../src/Vault.sol";
contract FuzzTest is Test {
Vault public vault;
function setUp() public {
vault = new Vault();
}
// Property: deposit then withdraw returns roughly same amount
function testFuzz_depositWithdraw(uint256 amount) public {
vm.assume(amount > 0 && amount <= 100 ether);
address user = address(0x1);
vm.deal(user, amount);
// Deposit
vm.startPrank(user);
vault.deposit{value: amount}();
// Withdraw
uint256 balance = vault.balanceOf(user);
vault.withdraw(balance);
vm.stopPrank();
// User should have approximately same ETH (minus fees)
uint256 finalBalance = user.balance;
assertApproxEqAbs(finalBalance, amount, 1000); // 1000 wei tolerance
}
// Property: total deposits equals contract balance
function testFuzz_totalDepositsEqualsBalance(uint256[] calldata amounts) public {
address[] memory users = new address[](amounts.length);
for (uint256 i = 0; i < amounts.length; i++) {
vm.assume(amounts[i] > 0 && amounts[i] <= 10 ether);
users[i] = address(uint160(i + 1));
vm.deal(users[i], amounts[i]);
vm.prank(users[i]);
vault.deposit{value: amounts[i]}();
}
// Invariant
assertEq(
address(vault).balance,
vault.totalDeposits(),
"Balance mismatch"
);
}
// Property: no one can withdraw more than deposited
function testFuzz_noOverdraw(uint256 deposit, uint256 withdraw) public {
vm.assume(deposit > 0 && deposit <= 100 ether);
vm.assume(withdraw > deposit);
address user = address(0x1);
vm.deal(user, deposit + 1 ether);
vm.startPrank(user);
vault.deposit{value: deposit}();
uint256 shares = vault.balanceOf(user);
// Should fail - can't withdraw more than deposited
vm.expectRevert();
vault.withdraw(shares + 1);
vm.stopPrank();
}
}
Fuzz Testing Tools
| Tool | Language | Strengths |
|---|---|---|
| Foundry Forge | Solidity | Fast, native |
| Echidna | Solidity | Property testing |
| Medusa | Solidity | Parallel testing |
| Hardhat | JavaScript | Ecosystem |
Coverage Analysis
Coverage Reports
# Generate coverage report
forge coverage
# Coverage with details
forge coverage --report lcov
# Coverage summary
forge coverage --summary
# Coverage for specific contract
forge coverage --match-contract Token
Coverage Metrics
| Metric | Description | Target |
|---|---|---|
| Line Coverage | % of lines executed | >95% |
| Branch Coverage | % of branches taken | >90% |
| Function Coverage | % of functions called | 100% |
| Statement Coverage | % of statements executed | >95% |
| Modifier Coverage | % of modifiers executed | 100% |
Coverage Report Example
| File | % Lines | % Branches | % Functions |
|---|---|---|---|
| src/Token.sol | 100.0% | 100.0% | 100.0% |
| src/Vault.sol | 95.5% | 90.0% | 100.0% |
| src/Governance.sol | 88.0% | 75.0% | 90.0% |
| ----------------------- | --------- | ------------ | ------------- |
| Total | 94.5% | 88.3% | 96.7% |
Coverage Improvement Strategy
| Priority | Action | Impact |
|---|---|---|
| High | Cover error paths | Catches edge cases |
| High | Test modifiers | Ensures access control |
| Medium | Cover events | Verifies logging |
| Medium | Test constants | Validates configuration |
| Low | Cover assembly | Low-level correctness |
Testing Tools Comparison
| Tool | Speed | Language | Best For |
|---|---|---|---|
| Foundry Forge | Fastest | Solidity | Unit/Fuzz tests |
| Hardhat | Fast | JavaScript | Integration tests |
| Echidna | Fast | Solidity | Property testing |
| Certora | Slow | CVL | Formal verification |
| Mythril | Slow | Solidity | Symbolic execution |
Real-World Testing: Aave V3
Testing Strategy
| Layer | Tools | Coverage |
|---|---|---|
| Unit | Forge | 100% functions |
| Integration | Hardhat | Critical flows |
| Fork | Foundry | Real state |
| Formal | Certora | Invariants |
| Fuzz | Echidna | Edge cases |
| Audit | Trail of Bits | Security |
Example: Testing Flash Loans
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
contract FlashLoanTest is Test {
IAavePool public pool;
function setUp() public {
vm.createSelectFork("mainnet", 18000000);
pool = IAavePool(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9");
}
// Test: Basic flash loan
function testFlashLoan() public {
address receiver = address(new MockFlashLoanReceiver());
uint256 amount = 1000 ether;
address asset = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"; // WETH
pool.flashLoan(
receiver,
asset,
amount,
"",
0,
0,
0
);
// Verify no debt (flash loan repaid)
assertEq(pool.getReserveData(asset).currentATokenBalance, 0);
}
// Fuzz: Flash loan with random amounts
function testFuzzFlashLoan(uint256 amount) public {
vm.assume(amount > 0 && amount <= 1000 ether);
// Test flash loan with various amounts
// ... implementation
}
}
Testing Checklist
## Smart Contract Testing Checklist
### Unit Tests
- [ ] All public functions tested
- [ ] All modifiers tested
- [ ] Edge cases covered (zero, max values)
- [ ] Error conditions tested
- [ ] Events verified
### Integration Tests
- [ ] Multi-contract interactions
- [ ] External protocol integrations
- [ ] State machine transitions
- [ ] Access control flows
### Fork Tests
- [ ] Mainnet state integration
- [ ] Real token interactions
- [ ] Protocol-specific testing
- [ ] Fuzz against real state
### Security Tests
- [ ] Reentrancy tested
- [ ] Overflow/underflow tested
- [ ] Access control verified
- [ ] Front-running considered
### Coverage
- [ ] Line coverage >95%
- [ ] Branch coverage >90%
- [ ] Function coverage 100%
- [ ] All error paths covered
### Formal Verification
- [ ] Critical invariants defined
- [ ] State machine verified
- [ ] Mathematical proof obtained
Trade-offs
| Decision | Option A | Option B | Recommendation |
|---|---|---|---|
| Testing Tool | Forge | Hardhat | Use both |
| Coverage Target | 100% | 95% | 95% minimum |
| Formal Verification | Always | Critical | Critical contracts only |
| Fork Testing | Every PR | Weekly | Weekly or on change |
Interview Questions
-
Explain the difference between unit testing, integration testing, and fork testing. When would you use each?
Unit testing tests individual functions in isolation (fast, cheap). Integration testing tests contract interactions (medium speed). Fork testing tests against real mainnet state (slow but realistic). Use unit tests for development, integration for workflows, fork for DeFi integration.
-
What is formal verification and when is it worth the investment?
Formal verification uses mathematical proofs to verify contract correctness. It's worth it for: high-value contracts (TVL > $10M), critical invariants (total supply, no overflow), and security-critical logic. It's expensive but provides mathematical certainty.
-
How do you measure test quality beyond line coverage?
Beyond line coverage, measure: branch coverage (all paths tested), mutation testing (tests catch bugs), property-based testing (invariants hold), and edge case coverage (boundary values tested). Also consider: error path coverage, event verification, and gas regression testing.
Quiz Questions
-
What is the primary benefit of fuzz testing over unit testing?
- A) Faster execution
- B) Random input generation
- C) Better coverage
- D) Lower cost
Answer: B - Fuzz testing generates random inputs to discover edge cases that manual tests miss.
-
What does invariant testing verify?
- A) Individual function behavior
- B) Contract interactions
- C) Properties that always hold true
- D) Gas efficiency
Answer: C - Invariant testing verifies that certain properties (invariants) remain true after any sequence of operations.
-
Which tool is best for formal verification of Solidity contracts?
- A) Foundry
- B) Hardhat
- C) Certora
- D) Slither
Answer: C - Certora provides formal verification using the Certora Verification Language (CVL) for mathematical proofs.