How to test overloaded initialize() functions


If you’ve tried testing your StandaloneERC721.sol contract from openzeppelin-eth, you’ll probably notice you get this frustrating error when you try to initialize your contract:

Error: Invalid number of parameters for "initialize". Got 5 expected 2!

It will probably drive you crazy for a bit of time, but the solution is pretty simple.

Basically, the truffle-contract doesn’t work for overloaded functions, so in the case of StandaloneERC721, there are multiple initialize functions, but when your test run, truffle just picks the first one it finds- which in the case of StandaloneERC721, isn’t the one you want.

To get around this, you need to specify which of the multiple initialize functions you want to call.

For a normal test you would expect to make the call something like this (your arguments might be different):

const tx = await StandaloneERC721.initialize(name, symbol, [address], [address], { from: owner, gas: 5000000 });

But this will give you this error:

Error: Invalid number of parameters for "initialize". Got 5 expected 2!

To get around this, use this line instead:

    const tx = await instance.methods["initialize(string,string,address[],address[])"](name, symbol,[owner], [owner], { from: owner, gas: 5000000 });

The reason this works is we are actually specifically picking our initialize function off the object under instance.methods, if you console.log(instance) you will find under methods each key for the different functions on your contract.

So, if you’ve been looking for a way to test overloaded Initialize functions, this should make your day a bit easier.

Can't "initialize" in tests