使用Truffle测试智能合约

我采用的是在本机的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

测试通过

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值