1

How can I compare two arrays in Solidity (with Truffle test framework)?

MyContract.sol --

pragma solidity 0.4.19;

contract MyContract {   
  uint[] public myArr;

  MyContract(uint[] _initArr) public {
    for (uint i=0; i < _initArr.length; i++) {
      myArr.push(_initArr[i]);
    }
  }

  function getMyArr public constant returns (uint[]) {
    return myArr;   
  } 
}

In Truffle test/TestMyContract.sol

pragma solidity 0.4.19;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/MyContract.sol";

contract TestMyContract {
  function testMyContract() public {
    uint[] storage expectedArr;
    expectedArr.push(0);
    expectedArr.push(1);
    expectedArr.push(2);

    MyContract myContract = new MyContract(expectedArr);

    Assert.equal(myContract.getMyArr(), expectedArr, "pass");
  }
}

"truffle test" gives error --

TypeError: Member "equal" is not available in type(library Assert) outside of storage.
        Assert.equal(myContract.getMyArr(), expectedArr, "pass");
        ^----------^

Is there a way to write unit test for Solidity arrays?

3

I'm not sure if this implementation works now.

But as having a hash collision is so so so... hard, you can hash the two different arrays and compare it's hashes. If this is possible to do, will be so much better than go to every index and check it. And also on gas-spending terms will be much more efficient.

Assert.equal(keccak256(expectedarr), keccack(myArr),"pass");

Let me know if it works for you.

0

as far as I know, you have to write an Assert.equal - Call for each value in your array.

Like so:

Assert.equal(expectedArr[0], myContract.myArr[0], “pass“);
Assert.equal(expectedArr[1], myContract.myArr[1], “pass“);
Assert.equal(expectedArr[2], myContract.myArr[2], “pass“);

Hope that helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.