繁体   English   中英

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

[英]How to test payable method in 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合约存储变量(请参阅测试以太交易 )。

其次,您没有正确调用deposit功能。 要调用函数并发送以太contract.functionName.value(valueInWei)(<parameter list>) ,格式为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");
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM