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: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: