How can we unit test contract private functions using the Truffle framework?

Since Solidity doesn't have package access or reflection language features, standard private testing approaches don't work.

Creating a test contract which inherits from the contract we're testing seems to be the only approach that works. However these tests would run on the blockchain.

Is there a way to unit test private functions from Javascript?


If they are internal functions you can inherit them and test them, if they are private functions, I believe the only way to unit test them is to make them public/internal, test them and then change them back to private once the tests are passing.

Another way to go about it would be to refactor your code so that the private functions are part of a library that you import into the contract. That way the functions are public in the library but not exposed in the actual contract.

  • 5
    I'm not sure that refactor your code for the tests is a good idea.. For now I'm looking for better solutions.
    – leonprou
    Feb 6 '18 at 10:14
  • I never said it was a good solution, but from my understanding it's one of the only solutions
    – Nanolucas
    Feb 7 '18 at 1:07
  • Yeah I see, thanks for answering. Looking into it more thorough I see how complex the issue is. As I understand, to do this we need to manipulate the compiled contract in our test suite.
    – leonprou
    Feb 8 '18 at 6:23

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.