我采用的是在本机的vscode中进行合约测试
首先新建一个Truffle-test的文件夹,用vscode来打开,在终端运行初始化命令,会自动生成要用到的各项文件。
truffle init
接着将写好的合约放到contracts文件夹下,这里我提前写了一个用来测试的合约,并将它命名为Counter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Counter {
uint256 public count;
function increment() public {
count++;
}
function getCount() public view returns (uint256) {
return count;
}
}
我们在写一份用来测试这个合约的js测试脚本,命名为Counter-test.js
const { expect } = require("chai");
const { ethers } = require("hardhat");
describe("Counter", function () {
let counter;
beforeEach(async function () {
const Counter = await ethers.getContractFactory("Counter");
counter = await Counter.deploy();
await counter.deployed();
});
it("Should initialize count to 0", async function () {
const initialCount = await counter.getCount();
expect(initialCount).to.equal(0);
});
it("Should increment the count", async function () {
await counter.increment();
const newCount = await counter.getCount();
expect(newCount).to.equal(1);
});
});
再写一份迁移脚本,命名为2_deploy_siimple_storage.js
const Counter = artifacts.require('Counter');
module.exports = function (deployer) {
deployer.deploy(Counter);
};
三个脚本编写好后,修改一下配置文件truffle-config.js
在终端运行命令,启动测试环境
truffle develop
在终端输入命令编译智能合约,运行后文件夹中会多出一个被编译的json文件Counter.json
compile
之后我们部署智能合约
migrate
接下来对合约进行测试
test
测试通过