测试合约

合约测试是合约开发流程中的一个重要环节,使用命令如下:

$ youbox test

之后会编译执行 test 目录下的测试脚本。

* ls ./test/
├── TestMetaCoin.sol // 测试合约
└── metacoin.js      // 测试用例

或者执行单独的测试脚本:

$ youbox test /path/to/testcase.js

测试用例样例:

// 获取合约
const MetaCoin = artifacts.require("MetaCoin");

contract('MetaCoin', (accounts) => {
  // 验证第一个账户获得初始 10000 MetaCoin
  it('should put 10000 MetaCoin in the first account', async () => {
      const metaCoinInstance = await MetaCoin.deployed();
      const balance = await metaCoinInstance.getBalance.call(accounts[0]);

      assert.equal(balance.valueOf(), 10000, "10000 wasn't in the first account");
  });
  // 验证调用方法需要依赖外部库
  it('should call a function that depends on a linked library', async () => {
      const metaCoinInstance = await MetaCoin.deployed();
      const metaCoinBalance = (await metaCoinInstance.getBalance.call(accounts[0])).toNumber();
      const metaCoinEthBalance = (await metaCoinInstance.getBalanceInEth.call(accounts[0])).toNumber();

      assert.equal(metaCoinEthBalance, 2 * metaCoinBalance, 'Library function returned unexpected function, linkage may be broken');
  });
}