3

I have a contract with a function marked as onlyOwner (from OpenZeppelin, so only the address that deployed the contract can call it).

pragma solidity ^0.4.17;

import "./Ownable.sol";

contract MyContract {

    function myFunction() public onlyOwner {
        dummy();
    }
}

I have created a Truffle/Solidity unit test for that contract but when I call the function I get an error, as the calling address is different than the address that deployed the contract.

pragma solidity ^0.4.17;

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

contract TestMyContract {
    MyContract contract = MyContract(DeployedAddresses.MyContract());

    function testCanCallFunction() public {
        myContract.myFunction();
    }
}

Is there a way to use the same address? And to do tests from different addresses? For example if I want to test with an owner and with another one. I know it can be done with Javascript tests.

Thanks!

1

You can assign a sender (as well as other transactional values) by including the data in the function call. In your specific example, you would do:

contract TestMyContract {
    MyContract contract = MyContract(DeployedAddresses.MyContract());

    function testCanCallFunction() public {
        myContract.myFunction({from: accounts[0]);
    }
}

accounts[0] is the default deployment account. By doing this, you are calling myContract.myFunction as the owner.

You can use any address you need in place of accounts[0].

  • I am aware of setting the sender address and other params in Javascript tests, but that can't be done in Solidity tests. Just to clarify, the test is written in Solidity as well. – Patricio Oct 24 '18 at 8:57

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.