本篇文章將帶你快速了解三大熱門測試環境:Ganache、Foundry 與 Hardhat Network。
這些工具不僅能幫你在本地模擬以太坊區塊鏈,還能提供快速部署、測試與除錯的便利。無論你是剛踏入 Web3 開發的新手,或是想提升開發效率的老手,都能從中找到適合自己的解法。
Ganache:以太坊測試鏈的老將
Ganache 由 Truffle 團隊推出,提供 GUI 與 CLI 兩種介面。GUI 讓人一眼就能看見交易記錄、區塊高度與帳戶餘額,適合視覺化操作;CLI 版本則能透過腳本快速產生多筆測試帳戶,方便自動化流程。
安裝方式
npm install -g ganache-cli # CLI 版本
ganache-cli --port 8545 --accounts 10 --defaultBalanceEther 1000
使用小技巧
- 預設每筆交易都會立即確認,適合快速迭代。
- 可利用
--deterministic 讓所有帳戶地址固定,方便寫測試。
Foundry:Rust + Solidity 的高效開發框架
Foundry 由 Paradigm 團隊打造,核心工具包括 forge(編譯、測試)與 cast(區塊鏈互動)。它採用 Rust 編譯器,編譯速度快且佔用記憶體小。
安裝方式
curl -L https://foundry.paradigm.xyz | bash # 下載並安裝
foundryup # 更新工具
forge init myproject
cd myproject
forge build
測試範例
在 src/Counter.sol 中寫一個簡單的計數器,接著於 test/Counter.t.sol 撰寫 Solidity 測試:
// Counter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract Counter {
uint256 count;
function increment() public { count += 1; }
function getCount() public view returns (uint256) { return count; }
}
// Counter.t.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "../src/Counter.sol";
contract CounterTest is Test {
Counter counter;
function setUp() public { counter = new Counter(); }
function testIncrement() public {
counter.increment();
assertEq(counter.getCount(), 1);
}
}
forge test --ffi
優點
- 不需要額外的測試鏈;
forge test 內建 anvil(類似 Ganache)
- 支援 Solidity 本身的測試語法,無需額外框架。
Hardhat Network:以太坊開發環境的萬用工具
Hardhat 本身是一個完整的開發框架,內建測試網路與部署工具。其 hardhat network 能在本機即時啟動區塊鏈,並支援多種插件。
安裝與啟動
npm init -y
npm install --save-dev hardhat
npx hardhat init # 建議先選擇腳本執行方式
在 hardhat.config.js 中設定網路:
module.exports = {
solidity: '0.8.19',
networks: {
hardhat: {},
localhost: { url: 'http://127.0.0.1:8545', chainId: 31337 }
},
};
測試範例(使用 JavaScript)
// test/Counter.js
const { expect } = require('chai');
const { ethers } = require('hardhat');
describe('Counter', function () {
let counter;
before(async function () { counter = await ethers.getContractFactory('Counter').deploy(); });
it('should increment', async function () { await counter.increment(); expect(await counter.getCount()).to.equal(1); });
});
npx hardhat test
這三者比較
| 工具 |
初學者友好度 |
編譯速度 |
內建測試鏈 |
生態系統 |
| Ganache |
★★★★ |
中等 |
內建 |
Truffle |
| Foundry |
★★★★☆ |
★★★★★ |
內建(Anvil) |
Paradigm |
| Hardhat |
★★★★☆ |
★★★★ |
內建 |
ethers.js, Waffle 等 |
小貼士
- 若你偏好 GUI,Ganache 是第一選擇;若追求最快編譯與測試速度,Foundry 會更適合。
- Hardhat 支援多種插件(如 Waffle、Ethers)與 TypeScript,適合需要完整開發流程的專案。
- 無論使用哪個工具,都建議先在本機執行
forge init 或 hardhat create 產生範例專案,快速上手。