[Ethereum] way to test an onlyOwner function from a Truffle/Solidity unit test

openzeppelin-contractssoliditytruffletruffle-testunittesting

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!

Best Answer

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].