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

How to test payable method in truffle?

我正在尝试在 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)) 错误。为什么?

您的测试合同有几个问题。首先是你没有初始化你的测试合约来持有任何以太币。因此,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");
  }
}