Ethereum教程

以太坊(Ethereum) – 智能合约测试(truffle test)

类似Java中JUnit单元测试工具,Trfuffle test可以帮助我们对智能合约项目进行白盒测试。
对于区块链项目,测试显得尤其重要,因为部署合约、迁移合约的成本都是相当高的,都要消耗Gas。

编写测试代码

现在让我们对前面章节中创建的智能合约,编写一些测试代码。整个测试过程模拟对智能合约 MyContract获取 value值、设置 value值的过程。
先确保 MyContract已经正确部署到Ganache本地区块链网络中。测试中将会用到Mocha测试框架,与Chai断言库,但Truffle已经集成了这些库。
测试代码用JavaScript编写,模拟与智能合约的交互,就像使用truffle console所做的那样。
在项目根目录下的 test目录中,添加测试脚本文件: MyContract.js
MyContract.js中的测试代码:
// 首先,`require`合约并将其分配给一个变量`MyContract`
const MyContract = artifacts.require('./MyContract.sol');
// 调用“contract”函数,并在回调函数中编写所有测试
// 回调函数提供一个“accounts”变量,表示本地区块链上的所有帐户。
contract('MyContract', (accounts) => {
    // 第1个测试:调用get()函数,检查返回值,测试合约中value初始值是否是: 'myValue'
    it('initializes with the correct value', async () => {
        // 获取合约实例
        const myContract = await MyContract.deployed()
        const value = await myContract.get()
        // 使用断言测试value的值
        assert.equal(value, 'myValue')
    })
    // 第2个测试: 调用set()函数来设置value值,然后调用get()函数来确保更新了值
    it('can update the value', async () => {
        const myContract = await MyContract.deployed()
        myContract.set('New Value');
        const value = await myContract.get()
        assert.equal(value, 'New Value')
    })
})
代码说明,请见注释。

运行测试脚本

执行命令行运行测试:
$ truffle test
测试详情:
G:\qikegu\ethereum\mydapp>truffle test
Using network 'development'.
Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.
  Contract: MyContract
    √ initializes with the correct value (76ms)
    √ can update the value (78ms)
  2 passing (188ms)
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4