Truffle Testing – How to Test Contract Functions with OnlyOwner Modifier

contract-deploymenttestingtruffle

I have a contract that inherits from Ownable, and some of its functions use onlyOwner modifier. I use truffle for local deployments to Ganache and testing.

Say, I have a contract:

contract MyContract is Ownable {
    function DoSomething() public view onlyOwner { return 1; }
}

A unit test for this contract is:

contract TestMyContract {
    MyContract c = MyContract(DeployedAddresses.CertifyingAgencies());
    function testDoSomething() {
        Assert.equal(c.DoSomething(), 1, "Shoudl equal 1");
    }
}

This test fails – onlyOwner modifier throws because msg.sender inside that modifier will be the address of the test contract, not the address of the owner/deployer.

How do I test such functions?

Best Answer

I've written test.js to show the example of how you can test this modifier:

var MyContract = artifacts.require("MyContract")

contract('MyContract', (accounts) => {

  let instance
  let owner = accounts[0]
  let account = accounts[1]

  beforeEach(async () => {
    instance = await MyContract.deployed()
  })

  it("should check restriction", async () => {
    try {
      let result = await instance.restrictedFunction.call({from: account})
      assert.equal(result.toString(), owner)
    } catch (e) {
      console.log(`${account} is not owner`)
    }
  })
})

In this example the test will not fail in both cases; I made it this way because it depends what result you are willing to get from this particular test. If you want it to fail if account is not owner, make this edit:

} catch (e) {
      assert.fail(null, null, `${account} is not owner`)
}
Related Topic