使用智能合約程式設計語言solidity編寫的智能合約,除了可以直接通過以太坊的工具鍊truffle,ganache-cli進行測試之外,還可以結合mocha進行單元測試。
mocha單元測試本質上,還是需要對合約進行編譯、部署,隻不過可以通過代碼的形式進行直覺的操作,而不是通過truffle指令來進行編譯、部署、測試。
首先,建構工程,我們可以根據建構node項目的方式建構:
添加依賴:package.json
"dependencies": {
"ganache-cli": "^6.12.2",
"mocha": "^8.2.1",
"solc": "^0.4.26",
"web3": "^1.3.3"
}
項目結構這裡簡單遵循以太坊項目的結建構立一個contracts檔案夾,用來儲存合約。然後在contracts目錄下建立HelloWorld.sol
pragma solidity ^0.4.23;
contract HelloWorld{
string public name;
constructor(string _name) public{
name = _name;
}
function getName() public view returns(string){
return name;
}
function changeName(string _name) public {
name = _name;
}
}
編寫compile.js用來編譯合約:
const path = require('path')
const fs = require('fs')
const solc = require('solc')
const filepath = path.resolve(__dirname,'contracts','HelloWorld.sol')
const source = fs.readFileSync(filepath,'utf8')
module.exports = solc.compile(source,1).contracts[":HelloWorld"]
建立test檔案夾,用來儲存測試代碼,編寫mocha測試代碼:helloworld.test.js
const ganache = require('ganache-cli')
const Web3 = require('web3')
const assert = require('assert')
const web3 = new Web3(ganache.provider())
const {bytecode,interface} = require('../compile')
var helloworld;
var fetchAccounts;
beforeEach(async ()=>{
/*
web3.eth.getAccounts().then(fetchAccounts=>{
console.log(fetchAccounts)
})*/
fetchAccounts = await web3.eth.getAccounts()
helloworld = await new web3.eth.Contract(JSON.parse(interface))
.deploy({data:bytecode,arguments:['abc']})
.send({from:fetchAccounts[0],gas:'1000000'})
})
describe('HelloWorld',()=>{
it('deploy contract',()=>{
assert.ok(helloworld.options.address)
})
it('call static function',async ()=>{
const message = await helloworld.methods.getName().call()
assert.equal('abc',message)
})
it('call dynamic function',async ()=>{
await helloworld.methods.changeName('xyz').send({from:fetchAccounts[0]})
const message = await helloworld.methods.getName().call()
assert.equal('xyz',message)
})
})
代碼準備完畢,我們可以在package.json中配置測試scripts選項:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIwczX0xiRGZkRGZ0Xy9GbvNGL2EzXlpXazxSPr1mWwVzVhxmWywEMW1mY1RzRapnTtxkb5ckYplTeMZTTINGMShUYfRHelRHLwEzX39GZhh2css2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xyayFWbyVGdhd3LcV2Zh1Wa9M3clN2byBXLzN3btg3Pn5GcuYDN1IDNzIjM1ITMwEjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
之後,在指令行下運作單元測試:npm test
單元測試全部通過,表示智能合約編譯部署測試均正常,我們在進行測試的時候,傳入了很多參數,合約部署之後,每一次調用,都需要進行真實的交易,是以需要賬戶資訊,需要轉賬操作,這裡面有進行靜态方法調用,也有動态方法調用,因為智能合約編譯之後,函數調用都是異步操作,是以使用了sync await來異步轉同步,進而擷取調用結果。
以上代碼全部參考知乎系列視訊全棧react、nodejs結合區塊鍊項目而來,有興趣的可以從此進入:https://www.zhihu.com/people/ke-ai-de-xiao-tu-ji-71/zvideos?page=3