1. 使用Hardhat编写并运行第一个测试
任务说明
本案例目标是在 Hardhat 项目中为智能合约编写并运行第一个自动化测试。你将创建一个简单的计数器合约,使用 Hardhat Test 框架(基于 Mocha + Chai)编写测试用例,验证合约的初始状态与核心功能,并通过命令行运行测试获得通过/失败结果。
环境准备
确保已安装 Node.js(≥16.0)。在空目录中初始化项目并安装 Hardhat:
npm init -y
npm install --save-dev hardhat
npx hardhat init
在初始化向导中选择“Create a JavaScript project”,其余选项按默认确认。完成后项目包含 contracts/、test/、scripts/ 目录及 Hardhat 配置文件。
合约实现
在 contracts/ 目录下创建 Counter.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract Counter {
uint256 private count;
event Incremented(uint256 newCount);
constructor() {
count = 0;
}
function increment() external {
count += 1;
emit Incremented(count);
}
function getCount() external view returns (uint256) {
return count;
}
}
编写测试
在 test/ 目录下创建 Counter.test.js:
const { expect } = require("chai");
const { ethers } = require("hardhat");
describe("Counter", function () {
it("初始计数应为0", async function () {
const Counter = await ethers.getContractFactory("Counter");
const counter = await Counter.deploy();
await counter.waitForDeployment();
expect(await counter.getCount()).to.equal(0);
});
it("调用increment后计数增加1", async function () {
const Counter = await ethers.getContractFactory("Counter");
const counter = await Counter.deploy();
await counter.waitForDeployment();
await counter.increment();
expect(await counter.getCount()).to.equal(1);
});
it("increment应触发Incremented事件", async function () {
const Counter = await ethers.getContractFactory("Counter");
const counter = await Counter.deploy();
await counter.waitForDeployment();
await expect(counter.increment())
.to.emit(counter, "Incremented")
.withArgs(1);
});
});
运行测试
在项目根目录执行:
npx hardhat test
验证方法与判定标准
运行上述命令后,观察终端输出。若三个测试用例全部通过,你会看到类似 3 passing 的汇总信息,且无失败或报错输出,即表示测试运行成功。若某个用例失败,Hardhat 会显示具体断言错误与堆栈信息,可根据提示修正合约或测试代码后重新运行。
预期输出
测试全部通过时,终端会显示类似以下汇总(具体版本号可能不同):
Counter
✔ 初始计数应为0
✔ 调用increment后计数增加1
✔ increment应触发Incremented事件
3 passing (1s)
该输出为确定性结果,由上述代码逻辑直接推出。若测试失败,Hardhat 会显示具体错误位置与断言信息,请根据提示检查合约逻辑或测试代码。