1

我正在使用 Truffle 和 TestRPC 开发以太坊合约。但是我无法获取要更新的状态变量。我认为可能只是我访问它太早了,但其他示例测试似乎工作得很好并且非常相似。

我已将我的合同缩减为最简单的可能破坏的事情:

pragma solidity ^0.4.11;

contract Adder {

    uint public total;

    function add(uint amount) {
        total += amount;
    }

    function getTotal() returns(uint){
        return total;
    }
}

这是我的测试:

var Adder = artifacts.require("./Adder.sol");

contract('Adder', accounts => {
  it("should start with 0", () =>
    Adder.deployed()
      .then(instance => instance.getTotal.call())
      .then(total => assert.equal(total.toNumber(), 0))
  );

  it("should increase the total as amounts are added", () =>
    Adder.deployed()
      .then(instance => instance.add.call(10)
        .then(() => instance.getTotal.call())
        .then(total => assert.equal(total.toNumber(), 10))
      )
  );

});

第一次测试通过了。但第二次测试失败,因为getTotal仍然返回 0。

4

1 回答 1

5

我相信问题在于您总是在使用该.call()方法。

实际上,此方法将执行代码但不会保存到区块链。

只有.call()在从区块链读取或测试throws.

只需删除.call()添加功能中的,它应该可以工作。

var Adder = artifacts.require("./Adder.sol");

contract('Adder', accounts => {
  it("should start with 0", () =>
    Adder.deployed()
      .then(instance => instance.getTotal.call())
      .then(total => assert.equal(total.toNumber(), 0))
  );

  it("should increase the total as amounts are added", () =>
    Adder.deployed()
      .then(instance => instance.add(10)
        .then(() => instance.getTotal.call())
        .then(total => assert.equal(total.toNumber(), 10))
      )
  );
});

另外,考虑instance在 promise 的函数链之外声明变量,因为上下文是不共享的。考虑使用async/await代替 Promise 进行测试。

var Adder = artifacts.require("./Adder.sol");

contract('Adder', accounts => {
  it("should start with 0", async () => {
    let instance = await Adder.deployed();
    assert.equal((await instance.getTotal.call()).toNumber(), 0);
  });

  it("should increase the total as amounts are added", async () => {
    let instance = await Adder.deployed();
    await instance.add(10);
    assert.equal((await instance.getTotal.call()).toNumber(), 10);
  });
});
于 2017-07-02T00:50:42.147 回答