以太坊(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)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值