Solidity: Unit testing internal functions

Daniel Que
Feb 25, 2018 · 1 min read

Writing unit tests for a contract with internal functions is a bit tricky. I’ll guide you through one of the possible solutions. Note that this works for internal, not private.

The basic idea is to write a derived contract which exposes the internal functions.

Let’s get started with a simple contract:

contract Contract {    function identity(uint a) internal returns (uint) {
return a;
}
}

Now we write a derived contract that exposes the internal identity() function. The convention is to add the prefix _ and to make this function public .

contract ExposedContract is Contract {    function _identity(uint a) public returns (uint) {
return identity(a);
}
}

Now we can test it in our test contract:

contract TestContract {    ExposedContract e;    function beforeEach() public {
e = new ExposedContract();
}
function testIdentity() public {
uint input = 5;
uint output = e._identity(input );
Assert.equal(output, input, "should equal input");
}
}

The above code is in this GitHub repo.

Daniel Que

Written by

Co-Founder of CryptoFin. Previously @ Uber, Hootsuite, UWaterloo.