0

For testing purposes, is there any way to replace a contract referenced by a hardcoded address with a mock?

I'm defining an interface in my contract

address interfaceAddress = 0x...;
IInterface if = IInterface(interfaceAddress);

But now I need to test against a mock version of this contract but don't know how without passing the interfaceAddress as an argument in the constructor. I do not want to do this because I'm interfacing with a lot of contracts and don't want to have to pass all of them in the constructor.

  • IInterface if = IInterface(interfaceAddress); couldn't possibly compile! – goodvibration Mar 7 '20 at 7:31
  • "I do not want to do this because I'm interfacing with a lot of contracts and don't want to have to pass all of them in the constructor": 1. You should know that this (passing them in the constructor, or even just to the specific function or functions which use them) is the correct way - both for testing and for actual runtime (what happens if you need to upgrade and redeploy one of them?). 2. It will actually yield LESS code in your contract - just pass IInterface x, which is one input argument instead of two lines of local variable declarations. – goodvibration Mar 7 '20 at 7:40
  • 3. You could deploy those contracts at those specific addresses in your Truffle tests, by using the exact same accounts used for deploying them to (I suppose) mainnet. You'll have to "roll" each account to the exact same nonce it was at when you deployed the real contract with it. Alternatively, if you're on Truffle 5.x + solc 0.5x or higher, then you can use the assembly opcode create2. I think that OpenZeppelin have wrapped that with something easier for you to use, so you might wanna check out their repo. – goodvibration Mar 7 '20 at 7:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.