章节
- 以太坊(Ethereum) – 是什么
- 以太坊(Ethereum) – 什么是智能合约
- 以太坊(Ethereum) – 以太币
- 以太坊(Ethereum) – 虚拟机(E.V.M.)
- 以太坊(Ethereum) – 分布式应用(DApp)
- 以太坊(Ethereum) – 账号(地址)
- 以太坊(Ethereum) – 虚拟机架构
- 以太坊(Ethereum) – 网络节点
- 以太坊(Ethereum) – 以太币单位
- 以太坊(Ethereum) – 挖矿
- 以太坊(Ethereum) – 智能合约开发
- 以太坊(Ethereum) – 智能合约的优点
- 以太坊(Ethereum) – 智能合约开发概述
- 以太坊(Ethereum) – 智能合约开发环境搭建
- 以太坊(Ethereum) – Ganache本地区块链
- 以太坊(Ethereum) – 开发智能合约
- 以太坊(Ethereum) – 部署智能合约到Ganache
- 以太坊(Ethereum) – 使用 truffle console 访问智能合约
- 以太坊(Ethereum) – 智能合约测试(truffle test)
- 以太坊(Ethereum) – 连接公链
- 以太坊(Ethereum) – 部署智能合约到公链
- 以太坊(Ethereum) – truffle脚本
- 以太坊(Ethereum) – 让浏览器支持区块链(MetaMask)
- 以太坊(Ethereum) – 智能合约前端页面
类似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)