如何测试松露中的应付方式?

时间:2018-08-28 19:53:27

标签: testing ethereum solidity smartcontracts truffle

我正在尝试在松露框架中测试智能合约的应付方式:

contract Contract {
  mapping (address => uint) public balances;

  function myBalance() public view returns(uint) {
    return balances[msg.sender];
  }

  function deposit() external payable {
    balances[msg.sender] += msg.value;
  }
}

contract TestContract {

  function testDeposit() external payable {
    Contract c = new Contract();

    c.deposit.value(1);

    Assert.equal(c.myBalance(), 1, "#myBalance() should returns 1");
  }
}

运行truffle test后,它失败,并显示TestEvent(result: <indexed>, message: #myBalance() should returns 1 (Tested: 0, Against: 1))错误。为什么?

1 个答案:

答案 0 :(得分:4)

您的测试合同有几个问题。首先是您没有初始化测试合约来持有任何以太币。因此,TestContract所持有的资金无法发送到Contract。为此,您需要设置一个initialBalance合约存储变量(请参见Testing ether transactions)。

第二,您没有正确调用deposit函数。要调用函数并发送以太币,格式为contract.functionName.value(valueInWei)(<parameter list>)

这是TestContract的固定版本:

contract TestContract {
  uint public initialBalance = 1 wei;

  function testDeposit() external payable {
    Contract c = new Contract();

    c.deposit.value(1)();

    Assert.equal(c.myBalance(), 1, "#myBalance() should returns 1");
  }
}