Solidity(松露):与松露控制台配合使用,但松露测试失败

时间:2017-10-14 22:54:08

标签: solidity truffle

我运行的truffle console运行正常,但truffle test失败。

代码是:

contract Geekt {
    address[] usersByAddress;  

  function registerNewUser(string handle, bytes32 city, bytes32 state, bytes32 country) public returns (bool success) {
    address newUserAddress = msg.sender;

    usersByAddress.push(newUserAddress);

    return true;
  }

  function getUsers() public constant returns (address[]) {
    return usersByAddress;
  }
}

测试是:

var Geekt = artifacts.require("Geekt");

contract('Geekt', function (accounts) {
  it('should get initial users as empty array', function () {
    return Geekt.deployed().then(function (instance) {
      return instance.getUsers.call();
    }).then(function (res) {
      assert.equal(res.length, 0, "Expected empty array after init.");
    });
  });

  it('should successfully add user', function () {
    var geekt;

    return Geekt.deployed().then(function (instance) {
      geekt = instance;

      return geekt.registerNewUser.call("elie222", "London", "State", "UK");
    }).then(function (res) {
      assert.equal(res, true, "Expected registerNewUser to return true.");
    }).then(function (res) {
      return geekt.getUsers.call();
    }).then(function (res) {
      // for debugging, but this assert passes: assert.equal(res.length, 0, "Expected array of size 0 after registerNewUser.");
      // res == [] so the next line fails:
      assert.equal(res.length, 1, "Expected array of size 1 after registerNewUser.");
    });
  });
});

它适用于松露控制台:

truffle(development)> Geekt.then(function(instance){return instance.registerNewUser("Tectract","Denver","CO","USA");})
{ tx: '0x8eeea303ff9f5ceee56d71fd1265da61991749aa3d5e82db0d2d630a98fd6eb5',
  receipt:
   { transactionHash: '0x8eeea303ff9f5ceee56d71fd1265da61991749aa3d5e82db0d2d630a98fd6eb5',
     transactionIndex: 0,
     blockHash: '0xf9a0da5ec0aba80a3338781f6d6414ceb43ec0fc023c31649a1cc347a4aba2ea',
     blockNumber: 14,
     gasUsed: 24566,
     cumulativeGasUsed: 24566,
     contractAddress: null,
     logs: [] },
  logs: [] }
truffle(development)> Geekt.then(function(instance){return instance.getUsers();})
[ '0x1a004a36a6bc9bcde42c6d2b237c6477cf0f535f' ]

怎么会发生这种情况?我做错了什么?

1 个答案:

答案 0 :(得分:0)

问题在于我正在进行call而不是transaction

事务更改状态,而方法调用不会,只能从网络读取。

您可以在此处详细了解: https://truffle.readthedocs.io/en/beta/getting_started/contracts/