在上一篇文章中,以太坊区块链与Nethereum的交互中我已经在dotnet客户端内硬编码了合约代码和ABI。它看起来很一般,我不太喜欢它!
此外,我没有使用truffle测试功能,因为我遇到了ganache-cli没有传播事件的问题。
首先,我创建了一个空文件夹,并运行:
truffle init
之后,我在合约文件夹中添加了合约。我不喜欢原始结构,因此我删除了构造函数参数并将事件更改为具有被乘数,乘数和乘积参数名称。
pragma solidity ^0.4.21;
contract Multiplier {
event Multiplied(uint256 indexed multiplicand, uint256 indexed multiplier, address indexed sender, uint256 product);
function multiply(uint256 a, uint256 b) public returns(uint r) {
// looks like an overflow waiting to happen
r = a * b;
emit Multiplied(a, b, msg.sender, r);
return r;
}
}
添加测试
接下来,我在合约中添加了简单的健全性检查。合约工件首先需要:
var Multiplier = artifacts.require("./Multiplier.sol");
然后,可以通过调用deployed()
方法来创建此合约的实例:
contract = await Multiplier.deployed();
之后你可以写测试了!Truffle js
测试带有异步/等待支持,这意味着更短,更易于理解的代码!
it("should multiply", async function () {
let res = await contract.multiply.call(4, 5);
assert.equal(res, 20);
})
起初,测试将失败并出现神秘错误。
1) Contract: Multiplier with deployment "before each" hook: deploy contract for "deploy":
Error: Multiplier has not been deployed to detected network (network/artifact mismatch)
at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-contract/contract.js:454:1
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
事实证明我忘记在迁移文件夹中添加2_deploy_contract.js
迁移文件:
var Multiplier = artifacts.require("./Multiplier.sol");
module.exports = function(deployer) {
deployer.deploy(Multiplier);
};
以下是完整的测试代码。当然,在生产代码中可以预期需要更多的测试。这是一个我保持简洁的样本。
var Multiplier = artifacts.require("./Multiplier.sol");
ccontract('Multiplier', function () {
let contract = null;
beforeEach('deploy', async function() {
co