1
pragma solidity ^0.4.23;

contract adding{

  uint256 public total;
  function  add(uint256 val1,uint256 val2) public returns(uint256){
    total = val1+val2;
    return total;
  }
}

The above code add two numbers

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

contract ('adding', function(accounts){

  it ("it will add two numbers", function(){
    return adding.deployed().then(function(i){
      instance = i ;
      return instance.add(3,4)
    }).then(function(value){
      assert.equal(value,7,"the values of 3 and 4 must be equal to 7" );
    });
  });
});

The above code is my unit test but the unit test fails. If I interact with my truffle console it will work

  Contract: adding
    1) it will add two numbers
    > No events were emitted


      0 passing (115ms)
      1 failing

      1) Contract: adding
           it will add two numbers:
         AssertionError: the values of 3 and 4 must be equal to 7: expected { Object (tx, receipt, ...) } to equal 7

I can see the following error in my console while running truffle test

2
  • Try checking value.toString() Commented Oct 16, 2018 at 6:12
  • i updated my code but getting same error passing (105ms) 1 failing 1) Contract: adding it will add two numbers: the values of 3 and 4 must be equal to 7 + expected - actual -[object Object] +7 Commented Oct 16, 2018 at 6:19

1 Answer 1

2

Any function that you call which requires a transaction will not return a value, but the transaction receipt. Instead, you can call that function, which will simply run the function on the local node, return the result, and not actually emit a transaction.

You would need to change your code to something like this:

return instance.add.call(3,4)

This will return the value from the function rather than the transaction receipt which you are getting back now from instance.add(3,4).

The other option is to make your function a view or pure function, which does not require a transaction to call and will return the value:

pragma solidity ^0.4.23;

contract adding{
  function add(uint256 val1,uint256 val2) public pure returns(uint256){
    uint256 total = val1+val2;
    return total;
  }
}

This should work without needing to call the function. Here, we made the total variable local to the function, so it does not store or read any data on the blockchain itself, and thus can be treated as a pure function.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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