Test to withdraw funds only by owner in solidity

Viewed 37

I need to write a test in solidity to test a withdrawFunds function. This function has an isOwner modifier which tests if the address of the sender is the same as the address stored as the owner's as part of the constructor. The problem is that when I try to invoke the withdrawFunds function, the function fails and says that I am not the owner. Is there any way I can test this functionality? Would proxy contracts help here? Any insight would be very helpful.

PS: I added an event to log the address stored as the owner's as part of the constructor (msg.sender) and to log the address the function receives as msg.sender. Both of these are different and I am not sure how to invoke this function as the owner.

1 Answers

In solidity you should define a function to return the contract owner:

// assuming you already set the owner in constructor
function getContractOwner() public view returns (address)
  {
    return owner;
  }

Then in test file

// accounts is passed by truffle. this testing in truffle environment
contract("YourContract", (accounts) => {

  let _contract = null;
  let buyer = null;
  // set the contract
  before(async () => {
    _contract = await YourContractName.deployed();
    buyer = accounts[1];
  });

  describe("Normal withdraw", () => {
    let currentOwner = null;
    before(async () => {
      currentOwner = await _contract.getContractOwner();
    });
    // now you have got the currentOwner
    it("should fail when withdrawing by different than owner address", async () => {
      const value = "10000000000000000";
      _contract.withdraw(value, { from: buyer });
      // add the logic for assertion
    });
}
}
Related