16

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?

2 Answers 2

19

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.

3
  • 10
    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, 2018 at 10:14
  • 2
    I never said it was a good solution, but from my understanding it's one of the only solutions
    – Nanolucas
    Feb 7, 2018 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, 2018 at 6:23
0

You can inherit the contract to a TestContract that has public methods that just call the private/internal methods. This way you can test the correctness of the methods in the original contract without modifying their visibility.

3
  • You cannot inherit private methods, as mentionned in the accepted answer already.
    – samlaf
    Feb 21 at 16:42
  • I guess you didn't read my answer. You inherit the original contract and ADD public methods that just call the private ones, not inherit them. Feb 23 at 8:15
  • Private functions can only be called from inside the contract; inherited contracts can't call them. solidity-by-example.org/visibility
    – samlaf
    Feb 23 at 16:58

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.